<?php

namespace App\Http\Services;

use App\Http\Model\CustomGame;
use App\Http\Services\FinanceRechargeOrderServices;
use App\Lib\Publisher;
use App\Http\Model\FinanceBeforeKk;
use App\Http\Model\FinanceCharm;
use App\Http\Model\FinanceDiamond;
use App\Http\Model\FinanceKk;
use App\Http\Model\FinanceProxy;
use App\Http\Model\FinanceRoomWallet;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\FinanceRoomWealth;
use App\Http\Model\FinanceGame;
use App\Http\Model\FinanceDebris;
use App\Http\Model\Hint;
use App\Http\Model\Room;
use App\Http\Model\System;
use App\Http\Model\SystemConfig;
use App\Http\Model\User;
use App\Http\Model\FinanceWealth;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Lib\SendSms;
use App\Http\Services\MsgServices;
use App\Http\Services\RoomMsgServices;
use App\Http\Model\Mall;
use App\Http\Model\FinanceJd;
use App\Http\Model\FinanceAgentDiamond;
use App\Http\Model\FinanceAgentGolod;
use App\Http\Model\Gift;
use App\Http\Model\GiftBag;
use App\Http\Model\Union;
use App\Http\Model\UnionUser;
use App\Http\Model\Friends;
use App\Http\Model\RoomUser;
use App\Http\Model\UserAgent;
use App\Http\Model\UserAgentGolod;
use App\Http\Model\RechargeBlack;
use App\Http\Model\Lyb;
use App\Http\Services\ContentCheckServices;
use App\Http\Model\Nameplate;
use Carbon\Carbon;
use App\Http\Services\UserServices;
use App\Http\Model\FinanceRechargeOrder;

/*财富service层*/

class FinanceServices extends CommonServices
{
    //全家总动员批量变更用户金豆数据
    protected $fcBatchChangeJdKey = 'FAMILYCOMPETITION:BATCHCHANGEJD';//string FAMILYCOMPETITION:WINNER => {string}

    protected $user;
    protected $diamond;
    protected $charm;
    protected $wealth;
    protected $room_wealth;
    protected $kk;
    protected $jd_model;
    protected $agentD_model;
    protected $agentG_model;
    protected $debris_model;
    protected $gift_model;
    protected $giftBag_model;
    protected $model_finance_proxy;
    protected $wealthChartsConf = [
        1=>'CACHE:FINANCE:WEALTH:CHARTS:DAY',
        2=>'CACHE:FINANCE:WEALTH:CHARTS:WEEK',
        3=>'CACHE:FINANCE:WEALTH:CHARTS:ALL',
    ];//富豪榜redis名称配置
    protected $charmChartsConf = [
        1=>'CACHE:FINANCE:CHARM:CHARTS:DAY',
        2=>'CACHE:FINANCE:CHARM:CHARTS:WEEK',
        3=>'CACHE:FINANCE:CHARM:CHARTS:ALL',
    ];
    protected $roomCharmChartsConf = [
        1=>'CACHE:FINANCE:ROOM:CHARM:CHARTS:DAY',
        2=>'CACHE:FINANCE:ROOM:CHARM:CHARTS:WEEK',
        3=>'CACHE:FINANCE:ROOM:CHARM:CHARTS:ALL',
    ];
    protected $roomWealthChartsConf = [
        1=>'CACHE:FINANCE:ROOM:WEALTH:CHARTS:DAY',
        2=>'CACHE:FINANCE:ROOM:WEALTH:CHARTS:WEEK',
        3=>'CACHE:FINANCE:ROOM:WEALTH:CHARTS:ALL',
    ];
    protected $roomSelfWealthChartsConf = [
        1=>'CACHE:FINANCE:ROOM:SELF:WEALTH:CHARTS:DAY',
        2=>'CACHE:FINANCE:ROOM:SELF:WEALTH:CHARTS:WEEK',
        3=>'CACHE:FINANCE:ROOM:SELF:WEALTH:CHARTS:ALL',
    ];

    protected $wealthChartsExpireTime = 3600;//redis sortset 销毁时间
    protected $charmChartsExpireTime = 3600;//redis sortset 销毁时间
    protected $wealthExpireName = '_expire';
    protected $charmExpireName = '_expire';
    protected $wealthRatio = 10; //财富值to钻石换算比例

    protected $gameRankRewardGiftType = 101; //娱乐等级奖励礼物类型
    protected $agentSmsKey = 'AGENT:SMS:';//代理短信缓存
    protected $payOrderFiveMinutes = 'PAY:ORDER:FIVE:MINUTES:';//string 用户未支付3次缓存
    protected $payOrderFiveMinutesCount = 'PAY:ORDER:FIVE:MINUTES:COUNT:';//记录加入3次未支付的次数


    private $model_room;
    private $model_finance_user_wallet;
    protected $room_services;
    protected $model_finance_room_wallet;
    protected $model_finance_before_kk;

    protected $lybModel;
    protected $modelFinanceRoomWealth;
    protected $model_system;
    protected $mall_model;
    protected $msgServices;
    private $unionUserModel;
    private $model_friends;
    private $gameModel;
    protected $roomUserModel;
    protected $roomMsgServices;
    protected $userAgentModel;
    protected $userAgentGolodModel;
    protected $rechargeBlackModel;
    protected $systemServices;
    protected $contentCheckService;
    protected $customModel;
    protected $nameplateModel;
    protected $unionModel;
    private $services_user;
    private $service_pay;
    protected $errorRechargeLog = 'error_rechargeBlack';

    public function __construct()
    {
        parent::__construct();

        $this->user = new User();
        $this->diamond = new FinanceDiamond();
        $this->charm = new FinanceCharm();
        $this->wealth = new FinanceWealth();
        $this->model_room = new Room();
        $this->model_finance_user_wallet = new FinanceUserWallet();
        $this->kk = new FinanceKk();
        $this->room_wealth = new FinanceRoomWealth();
        $this->model_finance_room_wallet = new FinanceRoomWallet();
        $this->modelFinanceRoomWealth = new FinanceRoomWealth();
        $this->model_finance_before_kk = new FinanceBeforeKk();
        $this->model_finance_proxy = new FinanceProxy();
        $this->model_system = new System();
        $this->mall_model = new Mall();
        $this->jd_model = new FinanceJd();
        $this->agentD_model = new FinanceAgentDiamond();
        $this->agentG_model = new FinanceAgentGolod();
        $this->debris_model = new FinanceDebris();
        $this->gift_model = new Gift();
        $this->giftBag_model = new GiftBag();
        $this->msgServices = new MsgServices();
        $this->unionUserModel = new UnionUser();
        $this->model_friends = new Friends();
        $this->gameModel = new FinanceGame();
        $this->roomUserModel = new RoomUser();
        $this->lybModel = new Lyb();
        $this->roomMsgServices = new RoomMsgServices();
        $this->userAgentModel = new UserAgent();
        $this->userAgentGolodModel = new UserAgentGolod();
        $this->rechargeBlackModel = new RechargeBlack();
        $this->systemServices = new SystemServices();
        $this->contentCheckService = new ContentCheckServices();
        $this->customModel = new CustomGame();
        $this->nameplateModel = new Nameplate();
        $this->unionModel = new Union();
        $this->services_user = new UserServices;
        $this->service_pay = new FinanceRechargeOrder;
    }

    //获取用户账户信息
    public function getUserCach()
    {
        $userInfo = $this->user->get_current_user();
        if (!empty($userInfo)) {
            $userId = $userInfo['user_id'];
            // 用户查看钱包时删除缓存 修正缓存数据不一致的问题
            $this->model_finance_user_wallet->delWalletCache($userId);
            //$walletInfo = $this->user->getUserWallet(['user_id' => $userId], ['diamond_balance', 'charm_balance', 'wealth_balance']);
            $walletInfo = $this->model_finance_user_wallet->get_wallet($userId);
            //$walletInfo['kk_balance'] = $walletInfo['kk_balance'] / 100;
            $walletInfo['today_kk_value'] = $this->kk->getUserToday($userId);
            $walletInfo['today_income'] = $this->kk->todayIncome($userId);
            $walletInfo['today_spending'] = $this->kk->todaySpending($userId);
            //$walletInfo['today_kk_value'] = $walletInfo['today_kk_value'] / 100;
            //充库存权限
            $finance_proxy = $this->model_finance_proxy->getProxyInfoByUserId($userId);
            $walletInfo['stock_status'] = empty($finance_proxy) ? 0 : 1;
            $rooms = $this->model_room->getSingle(['user_id' => $userId, 'certified' => 1], ['room_id']);
            $room_wealth_balance['room_is_certified'] = 0;
            $room_wealth_balance['room_wealth_balance'] = 0;
            $room_wealth_balance['room_wealth_balance_list'] = [];
            if(isset($rooms[0])) {
                $room_wealth_balance['room_is_certified'] = 1;
                $room_wealth_balance['room_wealth_balance'] = $this->get_finance_room_wealth_list($_SERVER['REQUEST_TIME'])['total'];
                $room_wealth_balance['room_wealth_balance_list'] = $this->get_finance_room_wealth_list_all($_SERVER['REQUEST_TIME']);
            }
            return array_merge($walletInfo, $room_wealth_balance);
        }
        return [];
    }

    //获取钻石充值规则
    public function getDiamondRule($plat_type)
    {
        $diamondInfo = $this->diamond->getDiamondRuleInfo(['plat_type' => $plat_type], ['rule_id', 'price', 'diamond_amount', 'diamond_desc', 'apple_product_id','corner','diamond_extra_num']);

        // $tradeConfig = config('pay.trade_type');
        // if ($plat_type == 1) {//IOS
        //     $out_data['trade_type'] = $tradeConfig['iOS'];
        // } elseif ($plat_type == 2) {//android
        //     $out_data['trade_type'] = $tradeConfig['android'];
        // } else {
        //     $out_data['trade_type'] = [];
        // }
        $itemList = [];
        //读配置
        $setting = $this->model_system->getPayRegisterTimeMoneyConfig('pay_register_time_money');
        if (!empty($setting)) {
            $userInfo = $this->user->get_current_user();
            $timeStamp = $userInfo['create_timestamp'] + ((int)$setting[0] * 86400);
            if ($timeStamp > time()) {
                foreach ($diamondInfo as $v) {
                    if ($v['price'] < $setting[1] * 100) {
                        $itemList[] = $v;
                    }
                }
            }else{
                $itemList = $diamondInfo;
            }
        }else{
            $itemList = $diamondInfo;
        }
        $out_data['itemlist'] = $itemList;
        // $out_data['recharge_ratio'] = $this->diamond->getRechargeRatio();
        $out_data['extraRate'] = 0;//支付宝充值奖励比例  百分位

        return $out_data;
    }

    public function getDiamondRulebyIos($ruleId){
        $data = $this->diamond->getDiamondRuleIos($ruleId);
        return $data;
    }

    /**
     * 获取支付类型
     */
    public function getPayTypeList($ua = []) {
        $config = $this->model_system->get_config();

        $userInfo = $this->user->get_current_user();
        if(empty($this->setpayTypeList($userInfo['user_id']))){
            $list = empty($config['pay_type_list']) ? [] : $config['pay_type_list']['value'];
            if(!empty($list)) {
            $list = json_decode($list, true);
             }
        }else{
            $list =$this->setpayTypeList($userInfo['user_id']);
        }


        $version = $ua[1];
        $payTypeMap = [
            '1' => [
                'pay_type' => 1,
                'pay_name' => '支付宝',
                'pay_url' => build_image('/chat/pay_icon_1.png'),
//                 'is_web' => 2 //$version >= '1.0.1' ? 2 : 1,//0APP内 1=外部浏览 2=内部浏览器
            ],
            '2' => [
                'pay_type' => 2,
                'pay_name' => '微信',
                'pay_url' => build_image('/chat/pay_icon_2.png'),
            ],
            '6' => [
                'pay_type' => 6,
                'pay_name' => '支付宝',
                'pay_url' => build_image('/chat/pay_icon_1.png'),
                'is_web' => 1 //$version >= '1.0.1' ? 2 : 1,//0APP内 1=外部浏览 2=内部浏览器
            ],
            '9' => [
                'pay_type' => 9,//三方微信
                'pay_name' => '微信',
                'pay_url' => build_image('/chat/pay_icon_2.png'),
                'is_web' => 1 //$version >= '1.0.1' ? 2 : 1,//0APP内 1=外部浏览 2=内部浏览器
            ],
            '10' => [
                'pay_type' => 10,//三方支付宝
                'pay_name' => '支付宝',
                'pay_url' => build_image('/chat/pay_icon_1.png'),
                'is_web' => 1,//0APP内 1=外部浏览 2=内部浏览器
            ],
            '11' => [
                'pay_type' => 11,//cibn支付宝
                'pay_name' => '支付宝',
                'pay_url' => build_image('/chat/pay_icon_1.png'),
            ],
            '12' => [
                'pay_type' => 12,//cibn支付宝
                'pay_name' => '支付宝',
                'pay_url' => build_image('/chat/pay_icon_1.png'),
            ],
            '13' => [
                'pay_type' => 13,//支付宝
                'pay_name' => '支付宝',
                'pay_url' => build_image('/chat/pay_icon_1.png'),
            ],
            '14' => [
                'pay_type' => 14,//微信
                'pay_name' => '微信',
                'pay_url' => build_image('/chat/pay_icon_2.png'),
            ],
            '15' => [
                'pay_type' => 15,//常富支付宝
                'pay_name' => '支付宝',
                'pay_url' => build_image('/chat/pay_icon_1.png'),
                'is_web' => 1 //$version >= '1.0.1' ? 2 : 1,//0APP内 1=外部浏览 2=内部浏览器
            ],
            '19' => [
                'pay_type' => 19,//ogw支付宝
                'pay_name' => '支付宝',
                'pay_url' => build_image('/chat/pay_icon_1.png'),
//                'is_web' => 1 //$version >= '1.0.1' ? 2 : 1,//0APP内 1=外部浏览 2=内部浏览器
            ],
            '20' => [
                'pay_type' => 20,//商福通支付宝
                'pay_name' => '支付宝',
                'pay_url' => build_image('/chat/pay_icon_1.png'),
                'is_web' => 1 //$version >= '1.0.1' ? 2 : 1,//0APP内 1=外部浏览 2=内部浏览器
            ],
            '21' => [
                'pay_type' => 21,//常富支付宝App
                'pay_name' => '支付宝',
                'pay_url' => build_image('/chat/pay_icon_1.png'),
//                'is_web' => 1 //$version >= '1.0.1' ? 2 : 1,//0APP内 1=外部浏览 2=内部浏览器
            ],
            '25' => [
                'pay_type' => 25,//杉德支付宝
                'pay_name' => '支付宝',
                'pay_url' => build_image('/chat/pay_icon_1.png'),
                //'is_web' => 1 //$version >= '1.0.1' ? 2 : 1,//0APP内 1=外部浏览 2=内部浏览器
            ],
            '26' => [
                'pay_type' => 26,//杉德微信
                'pay_name' => '微信',
                'pay_url' => build_image('/chat/pay_icon_2.png'),
                //'is_web' => 1
            ],
        ];

        $data = [];
        foreach($list as $type) {
            if(isset($payTypeMap[$type])) {
                $data[] = $payTypeMap[$type];
            }
        }

        return $data;
    }

    //获取魅力值流水列表
    public function getCharmStreamList($page, $page_size)
    {
        $userInfo = $this->user->get_current_user();
        if (!empty($userInfo)) {
            $userId = $userInfo['user_id'];
            $charmData = $this->charm->getCharmListData($userId, $page, $page_size);
            return ['list'=>$charmData,'page_index'=>$page,'page_count'=>count($charmData),'page_size'=>$page_size];
        }
        return ['list'=>[],'page_index'=>$page,'page_count'=>0,'page_size'=>$page_size];
    }

    //获取钻石流水列表
    public function getDiamondStreamList($page, $page_size)
    {

        $userInfo = $this->user->get_current_user();
        if (!empty($userInfo)) {
            $userId = $userInfo['user_id'];
            $diamondData = $this->diamond->getDiamondListData($userId, $page, $page_size);
            return ['list'=>$diamondData,'page_index'=>$page,'page_count'=>count($diamondData),'page_size'=>$page_size];
        }
        return ['list'=>[],'page_index'=>$page,'page_count'=>0,'page_size'=>$page_size];
    }

    //获取kk币流水列表
    public function getKkStreamList($page, $page_size)
    {

        $userInfo = $this->user->get_current_user();
        if (!empty($userInfo)) {
            $userId = $userInfo['user_id'];
            $diamondData = $this->kk->streams($userId, $page, $page_size);
            return [
                'list'=>$diamondData,
                'page_index'=>$page,
                'page_count'=>count($diamondData),
                'page_size'=>$page_size
            ];
        }
        return ['list'=>[],'page_index'=>$page,'page_count'=>0,'page_size'=>$page_size];
    }

    // 金币明细
    public function queryKKStreamByUserId($params)
    {
        $page = $params['page'] ?? 0;
        $limit = $params['limit'] ?? 10;
        $userId = $_SESSION['user_id'] ?? 0;
        if (empty($userId)) {
            return [];
        }
        $data = $this->kk->streams($userId, $page, $limit);

        return $data;
    }

    //获取财富等级列表
    public function getWealthRankList()
    {
        $rankData = $this->wealth->getWealthRankData();
        $treeData = $this->generateTree($rankData);
        return $treeData;
    }


    //获取魅力等级列表
    public function getCharmRankList()
    {
        $rankData = $this->charm->getCharmRankData();
        $treeData = $this->generateTree($rankData);
        return $treeData;
    }

    //获取富豪榜
    public function getWealthCharts($type,$page,$page_size)
    {
        $max_count = 50;
        if ($type == 3){
            $max_count = 100;
        }
        $page_index = $page * $page_size;
        if ($page_index > $max_count - 1){
            return ['list'=>[],'page_index'=>$page,'page_count'=>0,'page_size'=>$page_size];
        }
        if ($page_index + $page_size > $max_count){
            $page_size = $max_count - $page_index;
        }
        if ($page_size == 0){
            return ['list'=>[],'page_index'=>$page,'page_count'=>0,'page_size'=>$page_size];
        }

        $user = $this->user->get_current_user();

        if (in_array($type, [1,2,3])) {
            $charts = $this->wealth->get_user_charts($type, $page_index, $page_size);
            //昨天/上周/上个月 富豪榜
            $before_charts = $this->wealth->get_before_user_charts($type ,0 ,3);
            $rank_50 = $this->wealth->get_user_charts($type, 0, 50);
            if(!empty($user)){
                $my_wealth = $this->wealth->get_my_chart($type ,$user['user_id']);
            }
        } else {
            $previousType = $type - 3;
            $charts = $this->wealth->get_before_user_charts($previousType, $page_index, $page_size);
            $before_charts = [];
            $rank_50 = $this->wealth->get_before_user_charts($previousType, 0, 50);
            if(!empty($user)){
                $my_wealth = $this->wealth->get_before_my_chart($previousType ,$user['user_id']);
            }
        }

        $count = 0;
        foreach ($rank_50 as $kk=>$vv) {
            $count++;
            if($kk == $user['user_id']){
                break;
            }
        }

        if(!empty($user)){
//            $my_wealth = $this->wealth->get_my_chart($type ,$user['user_id']);
            $my_wallet = $this->model_finance_user_wallet->get_wallet($user['user_id']);
            $user['diamond_balance'] = $my_wallet['diamond_balance'];
            $user['charm_balance'] = $my_wallet['charm_balance'];
            $user['wealth_balance'] = $my_wallet['wealth_balance'];
            $user['jd_balance'] = $my_wallet['jd_balance'];
//            $user['game_balance'] = $my_wallet['game_balance'];
            $user['game_balance'] = empty($my_wallet['game_balance']) ? 1 : $my_wallet['game_balance'];
            $user['agent_jd_balance'] = $my_wallet['agent_jd_balance'];
            $user['debris_balance'] = $my_wallet['debris_balance'];
            $user['total_wealth_value'] = $my_wealth;
            $user['wealth_rank'] = ($count >= 50 || $my_wealth<1 ) ? -1 : $count;

            //用户铭牌
            $user['userNameplate'] = $this->nameplateModel->getNameplateByUserId($user['user_id']);
        }

        $now_list_id = array_keys($charts);
        $before_list_id = array_keys($before_charts);
        $list_id = array_merge($now_list_id ,$before_list_id);
        $map_user = [];
        $map_wallet = [];
        $data = [];

        $users = $this->user->get_users_by_ids($list_id);
        for ($i = 0; $i < count($users); $i++){
            $map_user[$users[$i]['user_id']] = $users[$i];
        }
        $wallets = $this->model_finance_user_wallet->get_wallets($list_id);
        for ($i = 0; $i < count($wallets); $i++){
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }
        foreach ($charts as $k=>$v){
            if(empty($map_user[$k])){
                continue;
            }
            $item = $map_user[$k];
            $item['diamond_balance'] = $map_wallet[$k]['diamond_balance'];
            $item['charm_balance'] = $map_wallet[$k]['charm_balance'];
            $item['wealth_balance'] = $map_wallet[$k]['wealth_balance'];
            $item['jd_balance'] = $map_wallet[$k]['jd_balance'];
//            $item['game_balance'] = $map_wallet[$k]['game_balance'];
            $item['game_balance'] = empty($map_wallet[$k]['game_balance']) ? 1 : $map_wallet[$k]['game_balance'];
            $item['agent_jd_balance'] = $map_wallet[$k]['agent_jd_balance'];
            $item['debris_balance'] = $map_wallet[$k]['debris_balance'];
            $item['total_wealth_value'] = intval($v);

            //用户铭牌
            $item['userNameplate'] = $this->nameplateModel->getNameplateByUserId($item['user_id']);

            $data[] = $item;
        }
        $data_before = [];
        foreach ($before_charts as $kk=>$vv){
            if(empty($map_user[$kk])){
                continue;
            }
            $item = $map_user[$kk];
            $item['diamond_balance'] = $map_wallet[$kk]['diamond_balance'];
            $item['charm_balance'] = $map_wallet[$kk]['charm_balance'];
            $item['wealth_balance'] = $map_wallet[$kk]['wealth_balance'];
            $item['jd_balance'] = $map_wallet[$kk]['jd_balance'];
//            $item['game_balance'] = $map_wallet[$kk]['game_balance'];
            $item['game_balance'] = empty($map_wallet[$kk]['game_balance']) ? 1 : $map_wallet[$kk]['game_balance'];
            $item['agent_jd_balance'] = $map_wallet[$kk]['agent_jd_balance'];
            $item['debris_balance'] = $map_wallet[$kk]['debris_balance'];
            $item['total_wealth_value'] = $vv;
            $data_before[] = $item;
        }

        return ['list'=>$data,'page_index'=>$page,'page_count'=>count($data),'page_size'=>$page_size ,'before_list'=>$data_before ,'my'=>$user];
    }

    /**
     * 获取房间财富榜
     * @param $room_id
     * @param $type 1.天、2.周、3.总 4.昨日 5上周
     * @param $page
     * @param $page_size
     * @return array
     */
    public function getRoomWealthCharts($userId, $room_id, $type,$page,$page_size)
    {
        $max_count = 50;
        if ($type == 3){
            $max_count = 100;
        }
        $page_index = $page * $page_size;
        if ($page_index > $max_count - 1){
            return ['list'=>[],'page_index'=>$page,'page_count'=>0,'page_size'=>$page_size];
        }
        if ($page_index + $page_size > $max_count){
            $page_size = $max_count - $page_index;
        }
        if ($page_size == 0){
            return ['list'=>[],'page_index'=>$page,'page_count'=>0,'page_size'=>$page_size];
        }
        $charts = $this->room_wealth->get_room_user_charts($type, $room_id, $page_index, $page_size);
        $list_id = array_keys($charts);
        $map_user = [];
        $map_wallet = [];
        $data = [];

        $users = $this->user->get_users_by_ids($list_id);
        for ($i = 0; $i < count($users); $i++){
            $map_user[$users[$i]['user_id']] = $users[$i];
        }
        $wallets = $this->model_finance_user_wallet->get_wallets($list_id);
        for ($i = 0; $i < count($wallets); $i++){
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }

        $ifShow = 0;//是否数据隐藏 0=隐藏 1=不隐藏
        do {
            //房间信息
            $roomInfo = $this->model_room->get_room($room_id);
            if(empty($roomInfo)) {
                break;
            }
            //房主不数据隐藏
            if($roomInfo['user_id'] == $userId) {
                $ifShow = 1;
                break;
            }
            //房间公会
            $unionInfo = $this->unionModel->getUnionByRoomId($room_id);
            if(empty($unionInfo) || ($unionInfo['stop']!=1) || ($unionInfo['authentication_status']<1)) {
                break;
            }
            //公会主播不数据隐藏
            $userUnionInfo = $this->unionModel->getUserUnionInfo($userId);
            if($userUnionInfo['id'] == $unionInfo['id']) {
                $ifShow = 1;
                break;
            }
            //房间管理员不数据隐藏
            $role = $this->model_room->get_role($room_id, $userId);
            if ($role > 0) {
                $ifShow = 1;
                break;
            }
        } while (false);

        for ($i = 0; $i < count($list_id); $i++){
            $item = $map_user[$list_id[$i]];
            $item['diamond_balance'] = $map_wallet[$list_id[$i]]['diamond_balance'];
            $item['charm_balance'] = $map_wallet[$list_id[$i]]['charm_balance'];
            $item['wealth_balance'] = $map_wallet[$list_id[$i]]['wealth_balance'];
            $item['jd_balance'] = $map_wallet[$list_id[$i]]['jd_balance'];
//            $item['game_balance'] = $map_wallet[$list_id[$i]]['game_balance'];
            $item['game_balance'] = empty($map_wallet[$list_id[$i]]['game_balance']) ? 1 : $map_wallet[$list_id[$i]]['game_balance'];
            $item['agent_jd_balance'] = $map_wallet[$list_id[$i]]['agent_jd_balance'];
            $item['debris_balance'] = $map_wallet[$list_id[$i]]['debris_balance'];
            $item['devote_diamond_total'] = intval($charts[$list_id[$i]]);
            $item['if_show'] = ($item['user_id'] == $userId) ? 1 : $ifShow;

            //用户铭牌
            $item['userNameplate'] = $this->nameplateModel->getNameplateByUserId($item['user_id']);

            $data[] = $item;
        }
        return ['list'=>$data,'page_index'=>$page,'page_count'=>count($data),'page_size'=>$page_size];
    }


    /**
     * 获取房间自己的财富榜
     * @param $type 1.天、2.周、3.总
     * @param $page
     * @param $page_size
     * @return array
     */
    public function getRoomSelfWealthCharts($type,$page,$page_size)
    {
        $max_count = 50;
        if ($type == 3){
            $max_count = 100;
        }
        $page_index = $page * $page_size;
        if ($page_index > $max_count - 1){
            return ['list'=>[],'page_index'=>$page,'page_count'=>0,'page_size'=>$page_size];
        }
        if ($page_index + $page_size > $max_count){
            $page_size = $max_count - $page_index;
        }
        if ($page_size == 0){
            return ['list'=>[],'page_index'=>$page,'page_count'=>0,'page_size'=>$page_size];
        }

        if (in_array($type, [1,2,3])) {
            $charts = $this->room_wealth->get_room_charts($type, $page_index, $page_size);
            //昨天/上周/上个月 富豪榜
            $before_charts = $this->room_wealth->get_before_room_charts($type ,0 ,3);
        } else {
            $previousType = $type - 3;
            $charts = $this->room_wealth->get_before_room_charts($previousType, $page_index, $page_size);
            //昨天/上周/上个月 富豪榜
            $before_charts = [];
        }

        $now_list_romm_id = array_keys($charts);
        $before_list_room_id = array_keys($before_charts);
        $list_romm_id = array_merge($now_list_romm_id ,$before_list_room_id);
        $map_room = [];
        $data = [];
        $rooms = $this->model_room->get_rooms_by_ids($list_romm_id);
        for ($i = 0; $i < count($rooms); $i++){
            $map_room[$rooms[$i]['room_id']] = $rooms[$i];
        }
        //重新排序若房间设置了隐藏则抛出
        foreach ($charts as $k=>$v){
            if(isset($map_room[$k]['is_hide']) && $map_room[$k]['is_hide'] == 1){
                continue;
            }
            $item = $map_room[$k];
            $item['total_wealth_value'] = intval($v);
            $data[] = $item;
        }
        // 提取需要排序的列
        $total_wealth_value = array_column($data, 'total_wealth_value');
        
        // 根据财富列重新排序数组
        array_multisort($total_wealth_value, SORT_DESC, $data);
        $before_data = [];
        foreach ($before_charts as $kk=>$vv){
            if(isset($map_room[$kk]['is_hide']) && $map_room[$kk]['is_hide'] == 1){
                continue;
            }
            $item = $map_room[$kk];
            $item['total_wealth_value'] = intval($vv);
            $before_data[] = $item;
        }

        // 提取需要排序的列
        $before_total_wealth_value = array_column($before_data, 'total_wealth_value');
        
        // 根据财富列重新排序数组
        array_multisort($before_total_wealth_value, SORT_DESC, $before_data);
        return ['list'=>$data,'page_index'=>$page,'page_count'=>count($data),'page_size'=>$page_size ,'before_list'=>$before_data];
    }

    //获取魅力榜
    public function getCharmCharts($type,$page,$page_size)
    {
        $max_count = 50;
        if ($type == 3){
            $max_count = 100;
        }
        $page_index = $page * $page_size;
        if ($page_index > $max_count - 1){
            return ['list'=>[],'page_index'=>$page,'page_count'=>0,'page_size'=>$page_size];
        }
        if ($page_index + $page_size > $max_count){
            $page_size = $max_count - $page_index;
        }
        if ($page_size == 0){
            return ['list'=>[],'page_index'=>$page,'page_count'=>0,'page_size'=>$page_size];
        }

        $user = $this->user->get_current_user();

        if (in_array($type, [1,2,3])) {
            $charts = $this->charm->get_user_charts($type, $page_index, $page_size);
            //昨天/上周/上个月 魅力榜
            $before_charts = $this->charm->get_before_user_charts($type ,0 ,3);
            $rank_50 = $this->charm->get_user_charts($type, 0, 50);
            if(!empty($user)){
                $my_charm = $this->charm->get_my_chart($type ,$user['user_id']);
            }
        } else {
            $previousType = $type - 3;
            $charts = $this->charm->get_before_user_charts($previousType, $page_index, $page_size);
            $before_charts = [];
            $rank_50 = $this->charm->get_before_user_charts($previousType, 0, 50);
            if(!empty($user)){
                $my_charm = $this->charm->get_before_my_chart($previousType ,$user['user_id']);
            }
        }

        $count = 0;

        foreach ($rank_50 as $kk=>$vv) {
            $count++;
            if($kk == $user['user_id']){
                break;
            }
        }

        if(!empty($user)){
//            $my_charm = $this->charm->get_my_chart($type ,$user['user_id']);
            $my_wallet = $this->model_finance_user_wallet->get_wallet($user['user_id']);
            $user['diamond_balance'] = $my_wallet['diamond_balance'];
            $user['charm_balance'] = $my_wallet['charm_balance'];
            $user['wealth_balance'] = $my_wallet['wealth_balance'];
            $user['jd_balance'] = $my_wallet['jd_balance'];
//            $user['game_balance'] = $my_wallet['game_balance'];
            $user['game_balance'] = empty($my_wallet['game_balance']) ? 1 : $my_wallet['game_balance'];
            $user['agent_jd_balance'] = $my_wallet['agent_jd_balance'];
            $user['debris_balance'] = $my_wallet['debris_balance'];
            $user['total_charm_value'] = $my_charm;
            $user['charm_rank'] = ($count >= 50 || $my_charm<1 ) ? -1 : $count;
        }

        $now_list_id = array_keys($charts);
        $before_list_id = array_keys($before_charts);
        $list_id = array_merge($now_list_id ,$before_list_id);
        $map_user = [];
        $map_wallet = [];

        $users = $this->user->get_users_by_ids($list_id);
        for ($i = 0; $i < count($users); $i++){
            $map_user[$users[$i]['user_id']] = $users[$i];
        }
        $wallets = $this->model_finance_user_wallet->get_wallets($list_id);
        for ($i = 0; $i < count($wallets); $i++){
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }

        $data = [];
        foreach ($charts as $k=>$v){
            if(empty($map_user[$k])){
                continue;
            }
            $item = $map_user[$k];
            $item['diamond_balance'] = $map_wallet[$k]['diamond_balance'];
            $item['charm_balance'] = $map_wallet[$k]['charm_balance'];
            $item['wealth_balance'] = $map_wallet[$k]['wealth_balance'];
            $item['jd_balance'] = $map_wallet[$k]['jd_balance'];
//            $item['game_balance'] = $map_wallet[$k]['game_balance'];
            $item['game_balance'] = empty($map_wallet[$k]['game_balance']) ? 1 : $map_wallet[$k]['game_balance'];
            $item['agent_jd_balance'] = $map_wallet[$k]['agent_jd_balance'];
            $item['debris_balance'] = $map_wallet[$k]['debris_balance'];
            $item['total_charm_value'] = $v;

            //用户铭牌
            $item['userNameplate'] = $this->nameplateModel->getNameplateByUserId($item['user_id']);

            $data[] = $item;
        }

        $data_before = [];
        foreach ($before_charts as $kk=>$vv){
            if(empty($map_user[$kk])){
                continue;
            }
            $item = $map_user[$kk];
            $item['diamond_balance'] = $map_wallet[$kk]['diamond_balance'];
            $item['charm_balance'] = $map_wallet[$kk]['charm_balance'];
            $item['wealth_balance'] = $map_wallet[$kk]['wealth_balance'];
            $item['jd_balance'] = $map_wallet[$kk]['jd_balance'];
//            $item['game_balance'] = $map_wallet[$kk]['game_balance'];
            $item['game_balance'] = empty($map_wallet[$kk]['game_balance']) ? 1 : $map_wallet[$kk]['game_balance'];
            $item['agent_jd_balance'] = $map_wallet[$kk]['agent_jd_balance'];
            $item['debris_balance'] = $map_wallet[$kk]['debris_balance'];
            $item['total_charm_value'] = $vv;
            $data_before[] = $item;
        }

        return ['list'=>$data,'page_index'=>$page,'page_count'=>count($data),'page_size'=>$page_size ,'before_list'=>$data_before,'my'=>$user];
    }


    /**
     * 获取房间魅力榜单
     * @param $room_id
     * @param $type 1.天、2.周、3.总 4昨日 5上周
     * @param $page
     * @param $page_size
     * @return array
     */
    public function getRoomCharmCharts($userId, $room_id, $type, $page, $page_size){
        $charts = $this->charm->get_room_user_charts($type, $room_id, $page * $page_size, $page_size);
        $list_id = array_keys($charts);
        $map_user = [];
        $map_wallet = [];
        $data = [];

        $users = $this->user->get_users_by_ids($list_id);
        for ($i = 0; $i < count($users); $i++){
            $map_user[$users[$i]['user_id']] = $users[$i];
        }
        $wallets = $this->model_finance_user_wallet->get_wallets($list_id);
        for ($i = 0; $i < count($wallets); $i++){
            $map_wallet[$wallets[$i]['user_id']] = $wallets[$i];
        }

        $ifShow = 0;//是否数据隐藏 0=隐藏 1=不隐藏
        do {
            //房间信息
            $roomInfo = $this->model_room->get_room($room_id);
            if(empty($roomInfo)) {
                break;
            }
            //房主不数据隐藏
            if($roomInfo['user_id'] == $userId) {
                $ifShow = 1;
                break;
            }
            //房间公会
            $unionInfo = $this->unionModel->getUnionByRoomId($room_id);
            if(empty($unionInfo) || ($unionInfo['stop']!=1) || ($unionInfo['authentication_status']<1)) {
                break;
            }
            //公会主播不数据隐藏
            $userUnionInfo = $this->unionModel->getUserUnionInfo($userId);
            if($userUnionInfo['id'] == $unionInfo['id']) {
                $ifShow = 1;
                break;
            }
            //房间管理员不数据隐藏
            $role = $this->model_room->get_role($room_id, $userId);
            if ($role > 0) {
                $ifShow = 1;
                break;
            }
        } while (false);

        for ($i = 0; $i < count($list_id); $i++){
            if (empty($map_user[$list_id[$i]])){
                continue;
            }
            $item = $map_user[$list_id[$i]];
            $item['diamond_balance'] = $map_wallet[$list_id[$i]]['diamond_balance'];
            $item['charm_balance'] = $map_wallet[$list_id[$i]]['charm_balance'];
            $item['wealth_balance'] = $map_wallet[$list_id[$i]]['wealth_balance'];
            $item['jd_balance'] = $map_wallet[$list_id[$i]]['jd_balance'];
//            $item['game_balance'] = $map_wallet[$list_id[$i]]['game_balance'];
            $item['game_balance'] = empty($map_wallet[$list_id[$i]]['game_balance']) ? 1 : $map_wallet[$list_id[$i]]['game_balance'];
            $item['agent_jd_balance'] = $map_wallet[$list_id[$i]]['agent_jd_balance'];
            $item['debris_balance'] = $map_wallet[$list_id[$i]]['debris_balance'];
            $item['total_charm_value'] = intval($charts[$list_id[$i]]);
            $item['if_show'] = ($item['user_id'] == $userId) ? 1 : $ifShow;

            //用户铭牌
            $item['userNameplate'] = $this->nameplateModel->getNameplateByUserId($item['user_id']);

            $data[] = $item;
        }
        return ['list'=>$data,'page_index'=>$page,'page_count'=>count($data),'page_size'=>$page_size];
    }

    /**
     * 获取房间真爱榜
     */
    public function getRoomTrueLoveRank($room_id,$page, $limit){
        $res = $this->gift_model->getRoomTrueLoveRank($room_id, $page, $limit);
        if(empty($res)){
            return [];
        }
        $userIds = array_unique(array_column($res,'user_id'));
        $senderUserids = array_unique(array_column($res,'from_user_id'));
        $giftIds = array_unique(array_column($res,'gift_id'));

        $userInfos = $this->user->get_users_by_ids($userIds);
        $sendUserInfo = $this->user->get_users_by_ids($senderUserids);
        $userInfos = array_column($userInfos,null,'user_id');
        $sendUserInfo = array_column($sendUserInfo,null,'user_id');

        //查询送礼人收礼人信息
        $final = [];
        foreach($res as $val){
            //获取礼物信息
            $giftInfo = $this->gift_model->get_gift($val['gift_id']);
            //收礼人信息
            $final[] = [
                'sender_name' => isset($sendUserInfo[$val['from_user_id']]) ? $sendUserInfo[$val['from_user_id']]['nickname'] : '神秘人',
                'sender_img' => isset($sendUserInfo[$val['from_user_id']]) ? $sendUserInfo[$val['from_user_id']]['images'][0] : '',
                'user_name' => isset($userInfos[$val['user_id']]) ? $userInfos[$val['user_id']]['nickname'] : '神秘人',
                'user_img' => isset($userInfos[$val['user_id']]) ? $userInfos[$val['user_id']]['images'][0] : '',
                'gift_img' =>  build_image($giftInfo['image']),
                'gift_num' => $val['gift_num'],
                'gift_name' => $giftInfo['name'],
                'gift_price' => $val['gift_price'],
                'time_stamp' => date('Y-m-d H:i:s',$val['change_timestamp'])
            ];
        }
        return  $final;
    }


    /**
     * 获取提现规则表
     * @return mixed
     */
    public function get_kk_rules(){
        return $this->kk->get_kk_rules();
    }


    function generateTree($array)
    {
        if (empty($array)) {
            return [];
        }
        $tree = [];
        foreach ($array as $k => $v) {
            if ($v['rank_pid'] == 0) {
                $tree[] = $v;
                unset($array[$k]);
            }
        }
        foreach ($tree as $key => $val) {
            foreach ($array as $k => $v) {
                if ($val['rank_id'] == $v['rank_pid']) {
                    unset($v['rank_id']);
                    unset($v['rank_pid']);
                    $tree[$key]['sub_rank'][] = $v;
                }
            }
            unset($tree[$key]['rank_id']);
            unset($tree[$key]['rank_pid']);
        }
        return $tree;
    }

    /**
     * 检测用户财富等级是否变化
     * @param $user_id
     * @return array|null
     */
    public function check_wealth_rank($user_id){
        $wallet = $this->model_finance_user_wallet->get_wallet($user_id);
        if (empty($wallet)){
            return null;
        }


        $data = $this->wealth->getNearWealthRank((int) $wallet['wealth_balance']);
        if (empty($data)){
            return null;
        }

        if ($data['rank_id'] < 2) {
            return null;
        }

        $old_rank_id = $this->wealth->get_user_rank($user_id);

        if ($old_rank_id == $data['rank_id']){
            return null;
        }
        $this->wealth->set_user_rank($user_id, $data['rank_id']);

        $data['wealth_balance'] = $wallet['wealth_balance']; //财富值

        return $data;
    }

    /**
     * 检测用户魅力等级是否变化
     * @param $user_id
     * @return array|null
     */
    public function check_charm_rank($user_id){
        $wallet = $this->model_finance_user_wallet->get_wallet($user_id);
        if (empty($wallet)){
            return null;
        }

        $data = $this->charm->getNearCharmRank($wallet['charm_balance']);
        if (empty($data)){
            return null;
        }

        if ($data['rank_id'] < 2) {
            return null;
        }

        $old_rank_id = $this->charm->get_user_rank($user_id);

        if ($old_rank_id == $data['rank_id']){
            return null;
        }
        $this->charm->set_user_rank($user_id, $data['rank_id']);

        $data['charm_balance'] = $wallet['charm_balance']; //魅力值

        return $data;
    }

    /**
     * 清除用户钱包缓存
     * @param $wealth_id
     */
    public function clear_cache($wealth_id){
        $this->wealth->clear_cache($wealth_id);
    }

    /**
     * 根据 $date 获取当前月得房间收益
     * @param string $date
     * @param int $room_id 单独查询某个房间
     * @return array
     */
    public function get_finance_room_wealth_list($date, $room_id = 0){
        $userInfo = $this->user->get_current_user();
        $room = $this->model_room->getSingle(['user_id' => $userInfo['user_id'],'certified' => 1],['room_id']);
        $room_id = $room_id ? $room_id : $room[0]['room_id'];
        $list = $this->room_wealth->getFinanceRoomWealthList($room_id, $date);
        $statisticsData = array_column($list,'total');
        $total = array_sum($statisticsData);
        return ['list' => $list, 'total' => $total];
    }

    /**
     * 房间收益详情
     * @param int $date 时间戳
     * @param int $page 起始页
     * @param int $length
     * @param int $roomId
     * @return array
     */
    public function get_finance_wealth_stream($startTime, $endTime, $page, $length, $roomId = 0){
        $userInfo = $this->user->get_current_user();
        $room = $this->model_room->getSingle(['user_id' => $userInfo['user_id'],'certified' => 1],['room_id']);
        if(!isset($room[0])) return [];

        //$list = $this->wealth->get_finance_wealth_stream($room[0]['room_id'], $date, $page, $length);
        $roomId = $roomId ? $roomId : $room[0]['room_id'];

        $list = $this->modelFinanceRoomWealth->getStream($roomId, $startTime, $endTime, $page, $length);
        if(empty($list)) return [];

        $from_user_ids = array_column($list, 'user_id');
        $from_user_ids = array_unique($from_user_ids);
        $from_user_ids = array_filter($from_user_ids);
        $from_user_ids = array_values($from_user_ids);
        $from_user = $this->user->get_users_by_ids($from_user_ids);
        $from_user_list = array_column($from_user,'nickname','user_id');

        $to_user_ids = array_column($list, 'from_user_id');
        $to_user_ids = array_unique($to_user_ids);
        $to_user_ids = array_filter($to_user_ids);
        $to_user_ids = array_values($to_user_ids);
        $to_user = $this->user->get_users_by_ids($to_user_ids);
        $to_user_list = array_column($to_user,'nickname','user_id');
        foreach ($list as $key => &$val) {
            //$val['user_name'] = $userInfo['nickname'];
            $val['user_name'] = $to_user_list[$val['from_user_id']];

            if(!$val['from_user_id']) continue;
            $val['from_user_name'] = $from_user_list[$val['user_id']];
        }
        unset($val);
        return $list;
    }


    /**
     * 房间收益总计
     * @param $startTime
     * @param $endTime
     * @return int|mixed
     */
    public function getFinanceWealthStreamTotal($startTime, $endTime ,$roomId = 0){
        if(!empty($roomId)){
            //如果一个用户有多个认证房间，房间流水对不上 sn修改
            return $this->modelFinanceRoomWealth->getStreamTotal($roomId, $startTime, $endTime);
        }
        $userInfo = $this->user->get_current_user();
        $room = $this->model_room->getSingle(['user_id' => $userInfo['user_id'],'certified' => 1],['room_id']);
        if(!isset($room[0])){
            return 0;
        }
        $roomId = $room[0]['room_id'];
        return $this->modelFinanceRoomWealth->getStreamTotal($roomId, $startTime, $endTime);
    }

    /**
     * 后台钻石-加减
     * @param $user_id
     * @param $diamond_balance
     */
    public function set_diamond_balance($user_id, $diamond_balance){
        if ($diamond_balance == 0){
            return;
        }
        $desc = '充值-系统充值';
        if ($diamond_balance < 0){
            $desc = '扣款-系统扣款';
        }
        DB::beginTransaction();
        $this->diamond->inc($user_id, 0, 0, 4, $diamond_balance, $desc);
        DB::commit();
    }

    /**
     * 金币兑换
     */
    public function exchange($kk_val,$accountPwd){
        $cur_user = $this->user->get_current_user();
        if (empty($cur_user)){
            return Hint::LOGIN_OUT;
        }

        $user_id = $cur_user['user_id'];
        //拦截黑名单 add by zxiaofee
        if((new UserFilterServices)->inExchangeAndWithdrawUserBlacklist($user_id)){
            return Hint::FINANCE_EXCHANGE_AND_WITHDRAW_BLACKLIST;
        }
        //对公结算公会会长不可金币兑换
        $unionInfo = $this->unionUserModel->getUnionInfoByUserId($user_id);
        if(!empty($unionInfo)) {
            if($unionInfo['settle_type'] == 2) {
                return Hint::FINANCE_JB_EXCHANGE_1;
            }
        }

        if (!redis_lock("withdraw". $user_id)){
            return Hint::NOT_ALLOWED;
        }
        $wallet = $this->model_finance_user_wallet->get_wallet($user_id);
        $kk_balance = $wallet['kk_balance'];
        if ($kk_balance < $kk_val){
            return Hint::KK_NOT_ENOUGH;
        }

        $configMap = [];
        $config = $this->systemServices->get_config();
        foreach ($config as $k => $v){
            $value = $v['value'];
            if ($v['type'] == 1){
                $value = intval($v['value']);
            }
            $configMap[$k] = $value;
        }
        $kk_to_diamond=$configMap['kk_to_diamond'];
        $diamond_val = (int) ($kk_val * $kk_to_diamond);

        DB::beginTransaction();
        try {
            $this->diamond->inc($user_id, 0, 0, 5, $diamond_val, "金币兑换钻石");
            $this->kk->inc($user_id, 0, 0, 6, -$kk_val, "金币兑换钻石");

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            write_log('error_finance', 'exchange', ['msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
        }
        redis_unlock("withdraw". $user_id);

        return array('code'=>Hint::SUCCESS ,'user_id'=> '');
    }

    /**
     * 校验账户是否设置密码
     * */
    public function checkAccountPassword()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [
            'account_password_status' => 0,
        ];

        do {
            $this->I('user_id', '用户ID', 'int', true, '用户ID不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $getWalletData = $this->model_finance_user_wallet->getSingle(['user_id'=>$this->requestData['user_id']],['user_id','account_password'],true);
            if(!empty($getWalletData['account_password'])){
                $data['account_password_status'] = 1;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 设置账户密码（设置密码、修改密码、忘记密码）
     * */
    public function setAccountPassword()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('user_id', '用户ID', 'int', true, '用户ID不能为空');
            $this->I('phone', '手机号', 'int', true, '手机号不能为空');
            $this->I('sms_code', '验证码', 'int', true, '验证码不能为空');
            $this->I('account_password', '账户密码', 'string', true, '账户密码不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $checkSmsCode = $this->model_finance_user_wallet->checkSmsCode($this->requestData['phone'],$this->requestData['sms_code']);
            if(!$checkSmsCode){
                $code = Hint::SMS_CODE_ERROR;
                $msg = Hint::getErrCodeMsg($code);
                break;
            }

            // 密码md5
            $accountPwdMd5 = md5($this->requestData['account_password']);

            // 判断密码是否一致
            $getWalletData = $this->model_finance_user_wallet->getSingle(['user_id'=>$this->requestData['user_id']],['user_id','account_password'],true);
            if($accountPwdMd5 == $getWalletData['account_password']) {
                $code = Hint::ERR_FAIL;
                $msg = '新密码不能与原密码一致';
                break;
            }

            // 更新密码
            $ret = $this->model_finance_user_wallet->singleUpdate(['user_id'=>$this->requestData['user_id']],['account_password'=>$accountPwdMd5]);
            if (!$ret) {
                $code = Hint::ERR_FAIL;
                $msg = '账户密码设置' . Hint::getErrCodeMsg($code);
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 后台扣除KK币(可添加)
     * @param $userId
     * @param $kkValue
     */
    public function minusKkValue($userId, $kkValue){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $kkValue = intval($kkValue);
            if ($kkValue == 0){
                $code = Hint::ERR_FAIL;
                $msg = '数量不能为空';
                break;
            }
            $desc = '金币提现扣除';
            if ($kkValue > 0){
                $desc = '金币系统发放';
            }

            DB::beginTransaction();
            try {

                if ($kkValue < 0) {
                    $wallet = $this->model_finance_user_wallet->get_wallet($userId);
                    $kk_balance = $wallet['kk_balance'];
                    if ($kk_balance < abs($kkValue)){
                        $code = Hint::KK_NOT_ENOUGH;
                        $msg = '金币不足';
                        break;
                    }
                }

                $this->kk->inc($userId, 0, 0, 7, $kkValue, $desc);

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_finance', 'minusKkValue', ['msg'=>$e->getMessage(), 'line'=>$e->getLine()]);

                $code = Hint::ERR_FAIL;
                $msg = $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');

    }

    /**
     * 金币系统操作
     * @param $userId
     * @param $kkValue
     * @param $desc
     */
    public function incKkValue($userId, $kkValue, $desc){
        $kkValue = intval($kkValue);
        if ($kkValue == 0){
            return;
        }

        DB::beginTransaction();
        try {
            $this->kk->inc($userId, 0, 0, 10, $kkValue, $desc);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            write_log('error_finance', 'incKkValue', ['msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
        }
    }

    /**
     * 活动返现 钻石充值
     * */
    public function diamondRecharge($params=[]){
        $code = Hint::SUCCESS;
        $data = [
            'request_params' => $params,
        ];

        do {
            try {
                $userId = $params['user_id'] ?? 0;
                $diamondNum = $params['diamond_num'] ?? 0;
                $msg = $params['msg'] ?? '';
                $type = $params['type'] ?? 7;
                if(empty($userId) or empty($diamondNum) or empty($msg)){
                    $code = Hint::ERR_PARAMS_CHECK_FAIL;
                    break;
                }



                // 活动返现充值
                DB::beginTransaction();
                $this->diamond->inc($userId, $userId, 0, $type, $diamondNum, $msg);
                DB::commit();


            } catch (Exception $e){
                $code = Hint::ERR_SYS_FAIL;
                $data['error_msg'] = Hint::getErrCodeMsg($code).':'.$e->getMessage();
                break;
            }
        }while(false);

        return compact('code','data');
    }

    /**
     * 钻石系统操作
     * @param $userId
     * @param $diamondValue
     * @param $desc
     */
    public function incDiamondValue($userId, $diamondValue, $desc){
        $diamondValue = intval($diamondValue);
        if ($diamondValue == 0){
            return;
        }
        DB::beginTransaction();
        $this->diamond->inc($userId, 0, 0, 10, $diamondValue, $desc);
        DB::commit();
    }

    ################# 后台调用 ##########################################
    /**
     * 用户钱包更新
     * */
    public function walletUpdate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            try {
                $this->I('wallet_id', '钱包ID', 'int', true, '钱包ID不能为空');
                $this->I('charm_to_kk', '金币比例', 'int', true, '金币比例不能为空');// 金币比例 = 魅力值
                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化
                $walletId = $this->requestData['wallet_id'];
                $ret = $this->model_finance_user_wallet->singleUpdate(['wallet_id' => $walletId], ['charm_to_kk' => $this->requestData['charm_to_kk']]);
                if (!$ret) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '用户钱包更新' . Hint::getErrCodeMsg($code);
                    break;
                }
                $data['wallet_id'] = intval($walletId);
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);
        return compact('code', 'msg', 'data');
    }


    /**
     * 根据 $date 获取用户所有房间当前月得房间收益
     * @param string $date
     * @return array
     */
    public function get_finance_room_wealth_list_all($date){
        $userInfo = $this->user->get_current_user();
        $room = $this->model_room->getSingle(['user_id' => $userInfo['user_id'],'certified' => 1],['room_id','name', 'room_uid', 'image']);

        $picDomain = getPicDomain();
        foreach ($room as $key => &$value) {
            $list = $this->room_wealth->getFinanceRoomWealthList($value['room_id'], $date);
            $value['image'] = $picDomain.$value['image'];
            $room[$key]['total'] = array_sum(array_column($list,'total'));
        }
        unset($value);
        return $room;
    }

    //定时同步房间财富值
    public function sync_room_wealth(){
        $cbd_room_ids = $this->model_room->getCbdRoomId();
        foreach ($cbd_room_ids as $cbd_room_id){
            $real_room_wealth = $this->modelFinanceRoomWealth->getStreamTotalV1($cbd_room_id ,strtotime(date('Y-m-d')) ,time());
            $redis_room_wealth = $this->modelFinanceRoomWealth->get_room_wealth_tmp($cbd_room_id);
            if($redis_room_wealth != $real_room_wealth){
                write_log('update_room_charts'.(isCli()?'-cli':''), '排行榜修复', ['cbd_room_id'=>$cbd_room_id,'real_room_wealth'=>$real_room_wealth,'redis_room_wealth'=>$redis_room_wealth]);
                $diff_wealth = $real_room_wealth-$redis_room_wealth;
                $this->modelFinanceRoomWealth->update_room_charts($diff_wealth ,$cbd_room_id);
            }
        }
    }

    /**校验每日消费是否达到上限
     * @param $user_id
     * @param $price
     * @return bool
     */
    public function checkDayConsumeIsOver($user_id ,$price){
        $today_consume = $this->diamond->getUserDayConsume($user_id);
        if($today_consume > $price){
            return true;
        }
        return false;
    }

    /**获取每日消费钻石限制
     * @return int
     */
    public function getDayConsumeLimit(){
        return $this->diamond->day_consume_limit ?? 40000;
    }

    /**校验警告开关+消费是否限额
     * @param $user_id 用户id
     * @param $price 本次消费金额
     * @param $alert_id 警告开关id
     * @return bool
     */
    public function checkAlertAndDayConsume($user_id ,$price, $alert_id){
        $switch = $this->model_system->get_system_alert($alert_id);
        if(!empty($switch) && $switch['switch'] ==1){
            if($price > $this->diamond->day_consume_limit){
                return true;
            }
            $today_consume = $this->diamond->getUserDayConsume($user_id);
            if($today_consume > $this->diamond->day_consume_limit - $price){
                return true;
            }
            return false;
        }
        return false;
    }

    /**获取每日消费钻石限制
     * @return int
     */
    public function reachConsumeToplimit($userId) {
        //判断是否达到限额
        $toplimit = (new SystemConfig())->getConsumeTopLimit();
        if ($toplimit == null) {
            return false;
        }
        $consumeTotal24 = $this->diamond->getUserConsume24($userId);
        if ($consumeTotal24 >= $toplimit) {
            return true;
        }
        return false;
    }

    /**
     * 检查神豪等级
     * @param int $score 榜单值
     * @return int
     */
    public function getRoomChampionLevel($score){
        $level = 1;
        if ($score < 100000) {
            $level = 1;
        } elseif ($score >= 100000 && $score < 520000) {
            $level = 2;
        } elseif ($score >= 520000) {
            $level = 3;
        }
        return $level;
    }

    /**
     * 购买商品赠送金豆
     */
    public function buyGoodGetJd($userId, $goodId, $num, $price, $timeLimit){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            //商品信息
            $skuId = 0;
            $goodInfo = $this->mall_model->getMallGoodByGoodsId($goodId);
            if(empty($goodInfo)) {
                $code = Hint::MALL_GOODS_LOWER;
                break;
            }
            $skuList = $this->mall_model->getSkuDataByGoods($goodId);
            if(empty($skuList[0])) {
                $code = Hint::MALL_GOODS_LOWER;
                break;
            }
            $skuId = $skuList[0]['sku_id'];
            //需要钻石
            $price = $price * $num;
            //有效期
            $timeLimit = $timeLimit * $num;
            //用户钱包
            $wallet = $this->model_finance_user_wallet->get_wallet($userId);
            if(empty($wallet)){
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            if( $wallet['diamond_balance'] < $price ){
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            //得到金豆
            $jdBalance = $price;

            //修改前用户的娱乐值
            $game_balance = empty($wallet['game_balance']) ? 1 : $wallet['game_balance'];

            //数据处理
            DB::beginTransaction();
            try {
                //商品增加
                $ret_data = $this->mall_model->shoppingAct(
                    $userId,
                    $userId,
                    $goodId,
                    $goodInfo['goods_name'],
                    $goodInfo['goods_type'],
                    $skuId,
                    $timeLimit,
                    $price,
                    $timeLimit,
                    time(),
                    1
                );

                $config = config('pay');

                //钻石
                $diamond_desc = $config['wallet_change_desc']['diamond_jd_shop_buy'];
                $this->diamond->inc($userId, $userId, 0, 100, 0-$price, $diamond_desc);

                //金豆
                $jd_desc = $config['wallet_change_desc']['jd_jd_shop_buy'];
                $this->jd_model->inc($userId, $skuId, 1, $jdBalance, $jd_desc);

                DB::commit();

                //娱乐等级处理
                $this->_userGameRankLevelPrivilege($userId);

                //用户娱乐等级升级全服公告
                $this->_userGameRankLevelNotice($userId, $game_balance);

                //MQ通知
                $mqData = [
                    'user_id' => $userId,
                    'jd_num' => $jdBalance,
                    'diamand_num' => $price
                ];
                $this->_mqSendActivity(1, $mqData);

            } catch (\Exception $e) {
                DB::rollBack();

                write_log('error_finance', 'buyGoodGetJd', ['msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //MQ通知
    protected function _mqSendActivity($type, $mqData) {
        try {
            $requestData = [
                'queue_route' => 'global.activity',
                'data' => [
                    'mqtype' => $type,
                    'mqData' => $mqData,
                    'create' => time()
                ],
            ];

            $publishObject = Publisher::getInstance();
            $publishObject->requestData = $requestData;
            $publishObject->publisher();
        } catch (\Exception $e) {
            write_log('error_mq', 'global.activity', ['requestData'=>$requestData]);
        }
    }

    /**
     * 全家总动员用户押注扣除金豆
     */
    public function fcJdDecr($user_id, $change_value, $data_id){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            //用户钱包
            $wallet = $this->model_finance_user_wallet->get_wallet($user_id);
            if(empty($wallet)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $change_value = abs($change_value);
            if($wallet['jd_balance'] < $change_value ){
                $code = Hint::JD_NOT_ENOUGH;
                break;
            }

            $config = config('pay');
            $jd_desc = $config['wallet_change_desc']['jd_qjzdy_decr'];
            //数据处理
            try {
                $this->jd_model->inc($user_id, $data_id, 52, $change_value, $jd_desc);
            } catch (\Exception $e) {
                write_log('error_finance', 'fcJdDecr', ['user_id'=>$user_id, 'data_id'=>$data_id, 'change_value'=>$change_value, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 全家总动员批量奖励用户金豆
     */
    public function fcJdIncreaseBatch(){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $info = Redis::GET($this->fcBatchChangeJdKey);
            $info = json_decode($info, 1);
            if(empty($info['gameNum']) || empty($info['list']) || empty($info['winner'])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //锁
            if (!redis_lock("fcJdIncreaseBatch". $info['gameNum'])){
                $code = Hint::NOT_ALLOWED;
                break;
            }

            $config = config('pay');
            $jd_desc = $config['wallet_change_desc']['jd_qjzdy_incr'];
            $data_id = $info['gameNum'];
            $winner = $info['winner'];
            $screenMin = $info['screenMin'];

            //金豆
            foreach($info['list'] as $val) {
                $user_id = $val['user_id'];
                $change_value = $val['num'];
                try {
                    $this->jd_model->inc($user_id, $data_id, 3, $change_value, $jd_desc);
                } catch (\Exception $e) {
                    write_log('error_finance', 'fcJdIncreaseBatch 全家总动员批量变更用户金豆 失败', ['data_id'=>$data_id, 'val'=>$val, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                    $code = Hint::ERR_FAIL;
                }
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 全家总动员批量发飘萍
     */
    public function fcFullScreenBatch(){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $info = Redis::GET($this->fcBatchChangeJdKey);
            $info = json_decode($info, 1);
            if(empty($info['gameNum']) || empty($info['list']) || empty($info['winner'])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //锁
            if (!redis_lock("fcFullScreenBatch". $info['gameNum'])){
                $code = Hint::NOT_ALLOWED;
                break;
            }

            $data_id = $info['gameNum'];
            $winner = $info['winner'];
            $screenMin = $info['screenMin'];

            //飘萍
            $userIds = array_column($info['list'], 'user_id');
            $users = $this->user->get_users_by_ids($userIds);
            $users = array_column($users, 'nickname', 'user_id');
            foreach($info['list'] as $val) {
                $user_id = $val['user_id'];
                $change_value = $val['num'];
                try {
                    if($change_value >= $screenMin) {
                        if(!empty($users[$user_id])) {
                            //获取用户娱乐等级
                            $gameRankInfo = $this->_getUserGameRankNum($user_id);
                            $gameLevel = empty($gameRankInfo['level']) ? 0 : $gameRankInfo['level'];
                            $fullId = 34;
                            //大帝
                            if(31<=$gameLevel && $gameLevel<=35) {
                                $fullId = 47;
                            }
                            //天神
                            if(36<=$gameLevel && $gameLevel<=40) {
                                $fullId = 52;
                            }
                            //天尊
                            if(41<=$gameLevel && $gameLevel<=45) {
                                $fullId = 57;
                            }

                            $this->msgServices->sendFullScreen($fullId,null,['userName'=>$users[$user_id], 'jdNum'=>$change_value],[]);
                        }
                    }
                } catch (\Exception $e) {
                    write_log('error_familyCompetition', 'fcJdIncreaseBatch 飘萍 失败', ['data_id'=>$data_id, 'val'=>$val, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                    $code = Hint::ERR_FAIL;
                }
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 西天取经发飘萍
     */
    public function xtqjFullScreen($type, $param){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            //获取用户娱乐等级
            if(!empty($param['userId'])) {
                $gameRankInfo = $this->_getUserGameRankNum($param['userId']);
            }
            $gameLevel = empty($gameRankInfo['level']) ? 0 : $gameRankInfo['level'];

            //悬赏奖励飘屏公告文案
            if($type == 38) {
                if(empty($param['userName']) || empty($param['giftStr'])) {
                    break;
                }
                $fullId = 38;
                //大帝
                if(31<=$gameLevel && $gameLevel<=35) {
                    $fullId = 46;
                }
                //天神
                if(36<=$gameLevel && $gameLevel<=40) {
                    $fullId = 51;
                }
                //天尊
                if(41<=$gameLevel && $gameLevel<=45) {
                    $fullId = 56;
                }
                $this->msgServices->sendFullScreen($fullId,null,['userName'=>$param['userName'], 'giftStr'=>$param['giftStr']],[]);
            }
            //西天取经2连击飘屏
            if($type == 37) {
                if(empty($param['userName']) || empty($param['skillStr']) || empty($param['itemStr']) || empty($param['giftStr'])) {
                    break;
                }
                $fullId = 37;
                //大帝
                if(31<=$gameLevel && $gameLevel<=35) {
                    $fullId = 44;
                }
                //天神
                if(36<=$gameLevel && $gameLevel<=40) {
                    $fullId = 49;
                }
                //天尊
                if(41<=$gameLevel && $gameLevel<=45) {
                    $fullId = 54;
                }
                $this->msgServices->sendFullScreen($fullId,null,['userName'=>$param['userName'], 'skillStr'=>$param['skillStr'], 'itemStr'=>$param['itemStr'], 'giftStr'=>$param['giftStr']],[]);
            }
            //西天取经3连抽飘屏
            if($type == 36) {
                if(empty($param['userName']) || empty($param['skillStr']) || empty($param['itemStr']) || empty($param['giftStr'])) {
                    break;
                }
                $fullId = 36;
                //大帝
                if(31<=$gameLevel && $gameLevel<=35) {
                    $fullId = 45;
                }
                //天神
                if(36<=$gameLevel && $gameLevel<=40) {
                    $fullId = 50;
                }
                //天尊
                if(41<=$gameLevel && $gameLevel<=45) {
                    $fullId = 55;
                }
                $this->msgServices->sendFullScreen($fullId,null,['userName'=>$param['userName'], 'skillStr'=>$param['skillStr'], 'itemStr'=>$param['itemStr'], 'giftStr'=>$param['giftStr']],[]);
            }
            //正常抽奖飘屏公告文案
            if($type == 35) {
                if(empty($param['userName']) || empty($param['itemStr']) || empty($param['giftStr'])) {
                    break;
                }
                $fullId = 35;
                //大帝
                if(31<=$gameLevel && $gameLevel<=35) {
                    $fullId = 43;
                }
                //天神
                if(36<=$gameLevel && $gameLevel<=40) {
                    $fullId = 48;
                }
                //天尊
                if(41<=$gameLevel && $gameLevel<=45) {
                    $fullId = 53;
                }
                $this->msgServices->sendFullScreen($fullId,null,['userName'=>$param['userName'], 'itemStr'=>$param['itemStr'], 'giftStr'=>$param['giftStr']],[]);
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 西天取经发礼物及金豆
     */
    public function sendGiftJd($param){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($param['userId']) || empty($param['giftList']) || empty($param['dataId']) || empty($param['jdType']) || empty($param['type'])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $param['giftList'] = json_decode($param['giftList'], true);
            if(empty($param['giftList'])) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            $userId = $param['userId'];
            $config = config('pay');
            $jd_desc = '';
            if($param['jdType'] == 10) {
                $jd_desc = $config['wallet_change_desc']['jd_xtqj_draw_incr'];
            }elseif($param['jdType'] == 11) {
                $jd_desc = $config['wallet_change_desc']['jd_xtqj_offer_incr'];
            }

            DB::beginTransaction();
            try {
                //发金豆
                //$this->jd_model->inc($userId, $param['dataId'], $param['jdType'], $param['jdNum'], $jd_desc);

                //发礼物
                $flag = 0;
                foreach($param['giftList'] as $val) {
                    if(empty($val['num'])) {
                        $flag = 1;
                        break;
                    }
                    //礼物
                    $res = $this->giftBag_model->inc((int)$userId, 0, (int)$val['gift_id'], (int)$val['num'], $param['type']);
                    if(!$res) {
                        $flag = 1;
                        break;
                    }
                }
                if($flag == 1) {
                    DB::rollBack();

                    write_log('error_finance', 'sendGiftJd 失败', ['param'=>$param]);
                    $code = Hint::ERR_FAIL;
                    break;
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();

                write_log('error_finance', 'sendGiftJd', ['param'=>$param, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 获取私聊扣费配置
     */
    public function msgPayConfig($userId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $config = config('pay');
            //语音通话每分钟消耗钻石数
            $data['voiceCallNeedNum'] = $config['voiceCallNeedNum'];
            //私聊每次消耗钻石数
            $data['privateMsgNeedNum'] = $config['privateMsgNeedNum'];

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 支付语音通话费用
     */
    public function payVoiceCall($userId, $callUserId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            //用户之间不可发起语音通话
            //是否有主播
            $unionUser = $this->unionUserModel->checkUnionUserByUserIds([$userId, $callUserId]);
            if(empty($unionUser)) {
                $code = Hint::PARAM_ERROR;
                $msg = '用户与用户之间不能发起语音通话';
                break;
            }

            $config = config('pay');
            //语音通话每分钟消耗钻石数
            $voiceCallNeedNum = $config['voiceCallNeedNum'];
            //语音通话每分钟主播分成金币比例
            $voiceCallRate = $config['voiceCallRate'];
            //语音通话每分钟主播分成金币数
            $voiceCallGetKk = round($voiceCallNeedNum*$voiceCallRate);
            //用户余额
            $diamondNow = $this->model_finance_user_wallet->getUserWalletDiamond($userId);
            if($diamondNow < $voiceCallNeedNum) {
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }

            DB::beginTransaction();
            try {
                //减钻石
                $diamond_desc = $config['wallet_change_desc']['diamond_mate_voice_call'];
                $this->diamond->inc($userId, $callUserId, 0, 72, 0-$voiceCallNeedNum, $diamond_desc);
                //加金币
                $kk_desc = $config['wallet_change_desc']['kk_mate_voice_call'];
                $this->kk->inc($callUserId, $userId, 0, 34, $voiceCallGetKk, $kk_desc);

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();

                write_log('error_finance', 'payVoiceCall', ['msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
                break;
            }

            //用户余额
            $diamondNow = $this->model_finance_user_wallet->getUserWalletDiamond($userId);
            $data['diamond_balance'] = $diamondNow;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 支付私聊费用
     */
    public function payPrivateMsg($userId, $callUserId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            //检查是否是好友
            $is_friends = $this->model_friends->is_friends($userId, $callUserId);
            if($is_friends) {
                break;
            }

            $config = config('pay');
            //私聊每次消耗钻石数
            $privateMsgNeedNum = $config['privateMsgNeedNum'];
            //私聊每次主播分成金币比例
            $privateMsgRate = $config['privateMsgRate'];
            //语音通话每分钟主播分成金币数
            $privateMsgGetKk = round($privateMsgNeedNum*$privateMsgRate);
            //用户余额
            $diamondNow = $this->model_finance_user_wallet->getUserWalletDiamond($userId);
            if($diamondNow < $privateMsgNeedNum) {
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }

            DB::beginTransaction();
            try {
                //减钻石
                $diamond_desc = $config['wallet_change_desc']['diamond_private_msg_call'];
                $this->diamond->inc($userId, $callUserId, 0, 73, 0-$privateMsgNeedNum, $diamond_desc);
                //加金币
                $kk_desc = $config['wallet_change_desc']['kk_private_msg_call'];
                $this->kk->inc($callUserId, $userId, 0, 35, $privateMsgGetKk, $kk_desc);

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();

                write_log('error_finance', 'payPrivateMsg', ['msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
                break;
            }

        } while (false);

        //用户余额
        $diamondNow = $this->model_finance_user_wallet->getUserWalletDiamond($userId);
        $data['diamond_balance'] = $diamondNow;

        return compact('code', 'msg', 'data');
    }

    //获取娱乐等级列表
    public function getGameRankList()
    {
        $list = $this->gameModel->getWealthRankData();
        return $list;
    }

    //获取用户娱乐等级
    public function getUserGameRank($userId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            //获取用户娱乐值
            $walletInfo = $this->model_finance_user_wallet->get_wallet($userId);
            $game_balance = empty($walletInfo['game_balance']) ? 1 : $walletInfo['game_balance'];
            //所有娱乐等级
            $rankList = $this->gameModel->getWealthRankData();
            //获取娱乐等级用户奖励领取记录
            $rewardList = $this->gameModel->getGameRankRewardListByUserid($userId);

            //用户当前娱乐等级
            $rankInfo = [];
            $userRewardList = [];
            foreach($rankList as $val) {
                if($val['min_value']<=$game_balance) {
                    $rankInfo = $val;
                }

                $active_item = [];
                foreach($val['active_item'] as $v2) {
                    //礼物
                    if($v2['data_type'] == 1) {
                        $giftInfo = $this->gift_model->get_gift($v2['data_id']);
                        $active_item[] = [
                            'data_type' => $v2['data_type'],
                            'name' => empty($giftInfo['name']) ? '' : $giftInfo['name'],
                            'image' => empty($giftInfo['image']) ? '' : $giftInfo['image'],
                            'gift_price' => empty($giftInfo['price']) ? 0 : $giftInfo['price'],
                            'day' => '',
                        ];
                    }
                    if($v2['data_type'] == 2) {
                        $goodInfo = $this->mall_model->getMallGoodByGoodsId($v2['data_id']);
                        $active_item[] = [
                            'data_type' => $v2['data_type'],
                            'name' => empty($goodInfo['goods_name']) ? '' : $goodInfo['goods_name'],
                            'image' => empty($goodInfo['small_img']) ? '' : build_image($goodInfo['small_img']),
                            'goods_type' => empty($goodInfo['goods_type']) ? 0 : $goodInfo['goods_type'],
                            'day' => round($v2['data_num']/86400).'天',
                        ];
                    }
                }

                $item = [
                    'level' => $val['level'],
                    'rank_name' => $val['rank_name'],
                    'status' => 0,//状态 0=未达到 1=未领取 2=已领取
                    'active_item' => $active_item,
                ];
                if(!empty($rewardList[$val['level']])) {
                    $item['status'] = empty($rewardList[$val['level']]['if_active_item']) ? 1 : 2;
                }
                $userRewardList[] = $item;


            }

            $rankInfo['user_id'] = $userId;
            $rankInfo['game_balance'] = $game_balance;
            $rankInfo['userRewardList'] = $userRewardList;

            $data = $rankInfo;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //用户领取娱乐等级奖励
    public function rewardUserGameRank($userId, $level)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            //获取娱乐等级用户奖励领取记录
            $rewardList = $this->gameModel->getGameRankRewardListByUserid($userId);
            if(empty($rewardList[$level])) {
                $code = Hint::PARAM_ERROR;
                $msg = '未解锁奖励，快去升级吧～';
                break;
            }
            if(!empty($rewardList[$level]['if_active_item'])) {
                $code = Hint::SAME_TIME_NOT_REPEAT;
                $msg = '奖励已领取,不可重复领取';
                break;
            }
            //所有娱乐等级
            $rankList = $this->gameModel->getWealthRankData();
            $rankList = array_column($rankList, null, 'level');
            if(empty($rankList[$level]['active_item'])) {
                $code = Hint::PARAM_ERROR;
                $msg = '该娱乐等级没有需要领取的奖励';
                break;
            }
            $reward = $rankList[$level]['active_item'];

            //锁
            $lock = redis_lock("LOCK:GAMERANK:REWARDACTIVE:".$userId.":".$level, 86400);
            if (!$lock) {
                continue;
            }
            $this->_sendUserGameRankReward($userId, 'if_active_item', $reward, $rewardList[$level]);

        } while (false);

        return compact('code', 'msg', 'data');
    }



    //更新用户娱乐等级并发升级权益
    public function _userGameRankLevelPrivilege($userId)
    {
        //获取用户娱乐值
        $walletInfo = $this->model_finance_user_wallet->get_wallet($userId);
        $game_balance = empty($walletInfo['game_balance']) ? 1 : $walletInfo['game_balance'];
        //所有娱乐等级
        $rankList = $this->gameModel->getWealthRankData();
        //获取娱乐等级用户奖励领取记录
        $rewardist = $this->gameModel->getGameRankRewardListByUserid($userId);

        //用户当前娱乐等级
        foreach($rankList as $val) {
            if($val['min_value']<=$game_balance) {
                //检查奖励
                if(!empty($val['active_item']) || !empty($val['passive_item'])) {
                    //是否有记录
                    if(empty($rewardist[$val['level']])) {
                        $log = [
                            'rank_id' => $val['rank_id'],
                            'level' => $val['level'],
                            'user_id' => $userId,
                            'if_active_item' => 0,
                            'if_passive_item' => 0,
                        ];
                        $this->gameModel->createGameRankRewardLog($log);
                    }
                }
            }
        }
        //获取娱乐等级用户奖励未领取升级下发奖励的记录
        $rewardist = $this->gameModel->getGameRankRewardListByNoPassive($userId);
        //下发奖励
        $rankList = array_column($rankList, null, 'level');
        foreach($rewardist as $val) {
            //锁
            $lock = redis_lock("LOCK:GAMERANK:REWARDPASSIVE:".$userId.":".$val['level'], 86400);
            if (!$lock) {
                continue;
            }
            //未领取
            if(empty($val['if_passive_item'])) {
                $reward = $rankList[$val['level']]['passive_item'];
                $this->_sendUserGameRankReward($userId, 'if_passive_item', $reward, $val);

            }
        }
    }

    //给用户发娱乐等级奖励
    private function _sendUserGameRankReward($userId, $type, $reward, $log)
    {
        //更新领取记录
        $res = $this->gameModel->updateGameRankRewardLog($log['id'], [$type=>1]);
        //下发奖励
        foreach($reward as $val) {
            //data_type 奖励类型 1=礼物 2=商品
            //data_num 礼物数量/商品时间

            DB::beginTransaction();
            try {
                //礼物
                if($val['data_type'] == 1) {
                    $res = $this->giftBag_model->inc((int)$userId, (int)$userId, (int)$val['data_id'], (int)$val['data_num'], $this->gameRankRewardGiftType);
                    if(!$res) {
                        DB::rollBack();
                        write_log('error_sendUserGameRankReward','发礼物失败', [$userId, $reward, $log]);
                        continue;
                    }
                }
                //商品
                if($val['data_type'] == 2) {
                    $goodInfo = $this->mall_model->getMallGoodByGoodsId($val['data_id']);
                    if(empty($goodInfo)) {
                        DB::rollBack();
                        write_log('error_sendUserGameRankReward','发商品失败 无法获取商品', [$userId, $reward, $log]);
                        continue;
                    }
                    $skuList = $this->mall_model->getSkuDataByGoods($val['data_id']);
                    if(empty($skuList[0])) {
                        DB::rollBack();
                        write_log('error_sendUserGameRankReward','发商品失败 无法获取商品sku', [$userId, $reward, $log]);
                        continue;
                    }
                    $skuId = $skuList[0]['sku_id'];
                    //商品增加
                    $res = $this->mall_model->shoppingAct(
                        0,
                        $userId,
                        $val['data_id'],
                        $goodInfo['goods_name'],
                        $goodInfo['goods_type'],
                        $skuId,
                        $val['data_num'],
                        0,
                        $val['data_num'],
                        time(),
                        2
                    );
                }

                DB::commit();

                //自动佩戴
                if($type=='if_passive_item' && $val['data_type']==2) {
                    //气泡
                    if($goodInfo['goods_type'] == 3) {
                        //是否有气泡
                        $userUseeGood = $this->mall_model->getUserUseGoods($userId, $goodInfo['goods_type']);
                        if(empty($userUseeGood)) {
                            $this->mall_model->setGoodsAttrie($userId, $res['id'], $goodInfo['goods_type']);
                        }
                    }
                    //娱乐头像框
                    if($goodInfo['goods_type'] == 8) {
                        $this->mall_model->setGoodsAttrie($userId, $res['id'], $goodInfo['goods_type']);
                    }
                    //游戏皮肤
                    if($goodInfo['goods_type'] == 9) {
                        $this->mall_model->setGoodsAttrie($userId, $res['id'], $goodInfo['goods_type']);
                    }
                }

            } catch (Exception $e){
                write_log('error_sendUserGameRankReward','发礼物失败', [$userId, $reward, $log,'message'=>$e->getMessage(),'line'=>$e->getLine()]);
                DB::rollBack();
            }
        }
    }

    //用户娱乐等级升级全服公告
    public function _userGameRankLevelNotice($userId, $oldGameBalance)
    {
        //获取用户娱乐值
        $walletInfo = $this->model_finance_user_wallet->get_wallet($userId);
        $game_balance = empty($walletInfo['game_balance']) ? 1 : $walletInfo['game_balance'];
        //所有娱乐等级
        $rankList = $this->gameModel->getWealthRankData();

        $oldLevel = 0;
        $newLevel = 0;
        $rankInfo = [];
        foreach($rankList as $val) {
            if($val['min_value']<=$oldGameBalance) {
                $oldLevel = $val['level'];
            }
            if($val['min_value']<=$game_balance) {
                $newLevel = $val['level'];
                $rankInfo = $val;
            }
        }
        //升级了触发公告
        if($newLevel > $oldLevel) {
            $levelStr = $rankInfo['rank_name'].'LV.'.$rankInfo['level'];
            $userInfo = $this->user->get_user($userId);

            $fullId = 0;
            //国王
            if(26<=$newLevel && $newLevel<=30) {
                $fullId = 39;
            }
            //大帝
            if(31<=$newLevel && $newLevel<=35) {
                $fullId = 40;
            }
            //天神
            if(36<=$newLevel && $newLevel<=40) {
                $fullId = 41;
            }
            //天尊
            if(41<=$newLevel && $newLevel<=45) {
                $fullId = 42;
            }

            if(!empty($fullId)) {
                $textParam = ['userName'=>$userInfo['nickname'], 'levelStr'=>$levelStr];
                $this->msgServices->sendFullScreen($fullId, null, $textParam, []);  
            }

            //公聊消息
            $roomId = $this->roomUserModel->get_user_cur_room($userId);
            if(!empty($roomId)) {
                $msg = '恭喜{un}娱乐等级达到{ls}，直播间全体膜拜～';
                $roomMsgData = [
                    "k" => 20007,
                    "uid" => $userId,
                    "un" => $userInfo['nickname'],
                    "ls" => $levelStr,
                    "msg" => $msg,
                ];
                $this->roomMsgServices->send_room_msg($roomId, $roomMsgData);
            }

            //私聊系统消息
            $msg = '恭喜您娱乐等级达到'.$levelStr.'，快去娱乐等级中心查看吧～';
            $this->msgServices->send_sys_text_msg($userId, $msg);
        }
    }

    //获取用户娱乐等级
    public function _getUserGameRankNum($userId)
    {
        //获取用户娱乐值
        $walletInfo = $this->model_finance_user_wallet->get_wallet($userId);
        $game_balance = empty($walletInfo['game_balance']) ? 1 : $walletInfo['game_balance'];
        //所有娱乐等级
        $rankList = $this->gameModel->getWealthRankData();

        $rankInfo = [];
        foreach($rankList as $val) {
            if($val['min_value']<=$game_balance) {
                $rankInfo = $val;
            }
        }

        return $rankInfo;
    }

    //用户代理状态
    public function agentStatus($userId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $info = $this->userAgentModel->getUserAgent($userId);
            $infogolod = $this->userAgentGolodModel->getUserAgent($userId);
            $data['status'] = empty($info['status']) ? 0 : $info['status'];
            $data['golodstatus'] = empty($infogolod['status']) ? 0 : $infogolod['status'];
            $data['rate'] = empty($info['rate']) ? 0 : $info['rate'];
            $data['hasPass'] = empty($info['password']) ? 0 : 1;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //代理发验证码
    public function agentSendSms($userId, $smsToken)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
//            $info = $this->userAgentModel->getUserAgent($userId);
//            if(empty($info)) {
//                $code = Hint::PARAM_ERROR;
//                $msg = '非代理用户';
//                break;
//            }
            //用户信息
            $userInfo = $this->user->get_user($userId, true);
            if(empty($userInfo)) {
                $code = Hint::LOGIN_OUT;
                break;
            }
            $phone = $userInfo['phone'];
            //查看配置是否启用阿里云短信验证码
            $alicodeConfig = $this->systemServices->getAliVerify();
            if($alicodeConfig['status'] == 1){
                if(empty($smsToken)){
                    $code = Hint::CHECK_CAPTCHA_CODE_ERROR;
                    $msg = '图形验证码错误';
                    break;
                }
                $cacheSms = Redis::get('ALI:VERIFY:TOKEN:'.$phone);
                if(($cacheSms != md5($phone)) || empty($cacheSms)){
                    $code = Hint::CHECK_CAPTCHA_CODE_ERROR;
                    $msg = '图形验证码错误';
                    break;
                }
            }

            //发送短信
            $expireTime = 5*60;
            $smsCode = randomkeys();
            $smsObj = new SendSms();

            if(env('APP_ENV') != 'product'){
                $redisKey = $this->agentSmsKey.$phone;
                Redis::setex($redisKey,300,'123456');
           
            } else {
                $result = $smsObj->spSendSingleSms($phone, $smsCode);
                if($result){
                    //redis 存储
                $redisKey = $this->agentSmsKey.$phone;

                Redis::setex($redisKey, $expireTime, $smsCode);

                }else{
                    $code = Hint::ERR_SYS_FAIL;
                    $msg = '短信发送失败';
                    break;
                }
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //代理设置密码
    public function agentSetPd($userId, $password, $sms_code)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
//            $info = $this->userAgentModel->getUserAgent($userId);
//            if(empty($info)) {
//                $code = Hint::PARAM_ERROR;
//                $msg = '非代理身份不可设置';
//                break;
//            }
            //用户信息
            $userInfo = $this->user->get_user($userId, true);
            if(empty($userInfo)) {
                $code = Hint::LOGIN_OUT;
                $msg = '用户信息获取失败';
                break;
            }

            //验证码
            $smsKey = $this->agentSmsKey.$userInfo['phone'];
            $sms_cache_code = Redis::get($smsKey);
            if ($sms_cache_code != $sms_code) {

                $code = Hint::SMS_CODE_ERROR;
                break;
            }

            Redis::DEL($smsKey);

            $res = $this->userAgentModel->agentUserSetPassword($userId, md5($password));

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //代理金币兑换钻石
    public function agentKkExchangeDiamond($userId, $needNum)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $needNum = abs(intval($needNum));
            $info = $this->userAgentModel->getUserAgent($userId);
            if(empty($info)) {
                $code = Hint::PARAM_ERROR;
                $msg = '非代理用户';
                break;
            }
            $rate = $info['rate'];//税率百分位
            //用户信息
            $userInfo = $this->user->get_user($userId, true);
            if(empty($userInfo)) {
                $code = Hint::LOGIN_OUT;
                $msg = '用户信息获取失败';
                break;
            }
            //余额
            $userWallet = $this->model_finance_user_wallet->get_wallet($userId);
            if(empty($needNum) || $userWallet['kk_balance']<$needNum) {
                $code = Hint::KK_NOT_ENOUGH;
                break;
            }
            $incrNum = intval($needNum - ($needNum*$rate)/100);

            //暂停代理操作
            $cacheKey = 'USER:AGENT:'.$userId;
            if (!redis_lock($cacheKey, 10)) {
                $code = Hint::SAME_TIME_NOT_REPEAT;
                break;
            }
            $config = config('pay');
            $kk_desc = $config['wallet_change_desc']['kk_exchange_agent'];
            $diamond_desc = $config['wallet_change_desc']['diamond_agent_exchange'];

            DB::beginTransaction();
            try {
                //扣除
                $this->kk->inc($userId, $userId, 0, 38, 0-$needNum, $kk_desc);

                //增加
                $this->diamond->inc($userId, $userId, 0, 85, $incrNum, $diamond_desc);

                DB::commit();

                $data['msg'] = '你已经成功兑换'.$incrNum.'钻石';
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $errMsg = ['msg'=>$e->getMessage(), 'line'=>$e->getLine()];
                // print_r($errMsg);
                DB::rollBack();
            }
            redis_unlock($cacheKey);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //代理转钻石到指定用户  , $sms_code, $password
    public function agentDiamondToUser($userId, $toUuid, $needNum)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $needNum = abs($needNum);
            $info = $this->userAgentModel->getUserAgent($userId);
            if(empty($info)) {
                $code = Hint::PARAM_ERROR;
                $msg = '非代理身份不可发送红包';
                break;
            }
            //用户信息
            $userInfo = $this->user->get_user($userId, true);
            if(empty($userInfo)) {
                $code = Hint::LOGIN_OUT;
                $msg = '用户信息获取失败';
                break;
            }
            //收用户信息
            $toUserInfo = $this->user->getUserByUuid($toUuid, true);
            if(empty($toUserInfo)) {
                $code = Hint::PARAM_ERROR;
                $msg = '该用户信息获取失败';
                break;
            }
            $toUserId = $toUserInfo['user_id'];
            //收用户 已注销 已封号
            $isForbid = $this->user->getBlockInfo($toUserId);
            if ($isForbid) {
                $code = Hint::USER_FORBID;
                $msg = '该用户已封禁，不可发送红包';
                break;
            }
            $isCancel = $this->user->getAccountCancel($toUserId);
            if ($isCancel || $toUserInfo['mobile_phone']==$toUserInfo['uuid']) {
                $code = Hint::USER_FORBID;
                $msg = '该用户已封禁，不可发送红包';
                break;
            }

            //判断是验证码还是密码
            $vType = 0;
//            if(!empty($sms_code)) {
//                $vType = 1;
//                //验证码
//                $smsKey = $this->agentSmsKey.$userInfo['phone'];
//                $sms_cache_code = Redis::get($smsKey);
//                if ($sms_cache_code != $sms_code) {
//                    $code = Hint::SMS_CODE_ERROR;
//                    break;
//                }
//            }elseif(!empty($password)) {
//                $vType = 2;
//                //密码
//                if(empty($info['password']) || $info['password']!==md5($password)) {
//                    $code = Hint::PASSWORD_ERROR;
//                    $msg = '代理密码错误';
//                    break;
//                }
//            }else{
//                $code = Hint::PARAM_ERROR;
//                $msg = '必要参数未传递';
//                break;
//            }

            //余额
            $userWallet = $this->model_finance_user_wallet->get_wallet($userId);
            if(empty($needNum) || $userWallet['diamond_balance']<$needNum) {
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }

            //暂停代理操作
            $cacheKey = 'USER:AGENT:'.$userId;
            if (!redis_lock($cacheKey, 10)) {
                $code = Hint::SAME_TIME_NOT_REPEAT;
                break;
            }
            $config = config('pay');
            $diamond_desc = $config['wallet_change_desc']['diamond_agent_out'];

            $log = [
                'user_id' => $toUserId,
                'from_user_id' => $userId,
                'diamond_num' => $needNum
            ];

            $logId = 0;

            DB::beginTransaction();
            try {
                //扣除
                $this->diamond->inc($userId, $toUserId, 0, 87, 0-$needNum, $diamond_desc);

                //添加记录
                $logId = $this->agentD_model->createAgentDLog($log);

                DB::commit();
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                DB::rollBack();
            }
            redis_unlock($cacheKey);

//            if($vType == 1) {
//                Redis::DEL($smsKey);
//            }

            //成功发信息
            if($code == Hint::SUCCESS) {
                $msg = $userInfo['nickname'].'给你发送了一个钻石红包，点击查收';
                $this->msgServices->agentDiamondSendMsg($userId, $toUserId, $msg, $logId, $needNum);
                // $this->msgServices->send_text_msg($userId, $toUserId, $msg);

                $msg = '您已经成功转账给用户'.$toUserInfo['nickname'].' , '.$needNum.'钻石';
                $this->msgServices->send_sys_text_msg($userId, $msg);
            }

            $this->userReceiveAgentDiamond($toUserId, $logId);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //用户领取转入的钻石
    public function userReceiveAgentDiamond($userId, $logId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $logInfo = $this->agentD_model->getAgentDLog($logId);
            if(empty($logInfo)) {
                $code = Hint::PARAM_ERROR;
                $msg = '红包信息获取失败';
                break;
            }
            if($logInfo['agentd_type'] != 1) {
                $code = Hint::PARAM_ERROR;
                $msg = '红包已领取';
                break;
            }

            //暂停代理操作
            $cacheKey = 'USER:AGENTJDRECEIVE:'.$logId;
            if (!redis_lock($cacheKey, 10)) {
                $code = Hint::SAME_TIME_NOT_REPEAT;
                break;
            }
            $config = config('pay');
            $diamond_desc = $config['wallet_change_desc']['diamond_agent_into'];

            DB::beginTransaction();
            try {
                //更新记录
                $this->agentD_model->updateAgentDLog($logId, ['agentd_type'=>2]);

                //增加
                $this->diamond->inc($logInfo['user_id'], $logInfo['from_user_id'], 0, 86, $logInfo['diamond_num'], $diamond_desc);

                DB::commit();
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                DB::rollBack();
                redis_unlock($cacheKey);
                break;
            }
            redis_unlock($cacheKey);

            $data['num'] = $logInfo['diamond_num'];

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //获取用户代理交易记录
    public function userAgentDLog($page, $page_size, $userId, $streamType, $timeSt, $timeEd)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $where['user_id'] = $userId;
            //转出
            if($streamType == 1) {
                $where['diamond_type'] = [87];
            }
            //兑换
            if($streamType == 2) {
                $where['diamond_type'] = [85];
            }
            $where['time_st'] = $timeSt;
            $where['time_ed'] = $timeEd;

            $list = $this->agentD_model->getAgentjStreamList($where, $page, $page_size);
            $listEx = [];
            if(!empty($list)) {
                $userIds = array_unique(array_column($list, 'from_user_id'));
                $users = $this->user->get_users_by_ids($userIds);
                $users = array_column($users, null, 'user_id');

                foreach($list as $key=>$val) {
                    $val['to_uuid'] = 0;
                    if($streamType == 1) {
                        $val['to_uuid'] = empty($users[$val['from_user_id']]['user_uid']) ? 0 : $users[$val['from_user_id']]['user_uid'];
                    }

                    $item = [];
                    $item['stream_id'] = $val['stream_id'];
                    $item['user_id'] = $val['user_id'];
                    $item['change_value'] = $val['diamond_value'];
                    $item['diamond_type'] = $val['diamond_type'];
                    $item['change_timestamp'] = $val['change_timestamp'];
                    if($streamType == 1) {
                        $item['to_uuid'] = $val['to_uuid'];
                    }
                    $listEx[] = $item;
                }
            }

            $data['list'] = $listEx;

        } while (false);

        return compact('code', 'msg', 'data');
    }



    /**
     * 荒漠捕牛变更幸运券
     */
    public function lcGiftNumChange($userId, $giftId, $changeValue){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if($changeValue < 0) {
                //现有数量
                $giftBagInfo = $this->giftBag_model->get(['user_id'=>$userId,'gift_id'=>$giftId], true);
                $bagNum = empty($giftBagInfo['avail']) ? 0 : $giftBagInfo['avail'];
                if(abs($changeValue) > $bagNum ){
                    $code = Hint::JD_NOT_ENOUGH;
                    $msg = '数量不足';
                    break;
                }
            }

            //数据处理
            DB::beginTransaction();
            try {
                //变更背包礼物
                $res = $this->giftBag_model->inc((int)$userId, 0, (int)$giftId, (int)$changeValue, 2007);
                if(!$res) {
                    DB::rollBack();
                    write_log('error_lassoCattle','lcGiftNumChange 变更背包礼物失败', [$userId, $giftId, $changeValue]);
                    $code = Hint::ERR_FAIL;
                    continue;
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_lassoCattle', 'lcGiftNumChange', ['user_id'=>$userId, 'giftId'=>$giftId, 'changeValue'=>$changeValue, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 荒漠捕牛批量发飘萍
     */
    public function lcFullScreenBatch($info){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($info['list'])) {
                break;
            }
            if(empty($info['gameNum']) || empty($info['winner'])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //锁
            if (!redis_lock("lcFullScreenBatch". $info['gameNum'])){
                $code = Hint::NOT_ALLOWED;
                break;
            }

            //飘萍
            $userIds = array_column($info['list'], 'user_id');
            $users = $this->user->get_users_by_ids($userIds);
            $users = array_column($users, 'nickname', 'user_id');
            foreach($info['list'] as $val) {
                try {
                    if($val['num'] >= $info['screenMin']) {
                        if(!empty($users[$val['user_id']])) {
                            $this->msgServices->sendFullScreen(59 ,null,['userName'=>$users[$val['user_id']], 'itemNum'=>$val['num']],[]);
                        }
                    }
                } catch (\Exception $e) {
                    write_log('error_lassoCattle', 'lcFullScreenBatch 飘萍 失败', ['gameNum'=>$info['gameNum'], 'val'=>$val, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                    $code = Hint::ERR_FAIL;
                }
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 开运装备星发飘萍
     */
    public function equipFullScreen($type, $param){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($param['userName']) || empty($param['itemName']) || empty($param['equipName'])) {
                break;
            }
            $this->msgServices->sendFullScreen($type,null,['userName'=>$param['userName'], 'itemName'=>$param['itemName'], 'equipName'=>$param['equipName']],[]);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 开运装备星抽奖扣除金豆
     */
    public function equipJdDecr($user_id, $change_value, $data_id){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            //用户钱包
            $wallet = $this->model_finance_user_wallet->get_wallet($user_id);
            if(empty($wallet)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $change_value = abs($change_value);
            if($wallet['jd_balance'] < $change_value ){
                $code = Hint::JD_NOT_ENOUGH;
                break;
            }

            $config = config('pay');
            $jd_desc = $config['wallet_change_desc']['jd_equip_draw_decr'];
            //数据处理
            try {
                $this->jd_model->inc($user_id, $data_id, 55, $change_value, $jd_desc);
            } catch (\Exception $e) {
                write_log('error_finance', 'equipJdDecr', ['user_id'=>$user_id, 'data_id'=>$data_id, 'change_value'=>$change_value, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 金币兑换金豆
     */
    public function kkBuyJd($userId, $num){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $kkNum = $num * 1;
            //用户钱包
            $wallet = $this->model_finance_user_wallet->get_wallet($userId);
            if(empty($wallet)){
                $code = Hint::KK_NOT_ENOUGH;
                break;
            }
            if($wallet['kk_balance'] < $kkNum){
                $code = Hint::KK_NOT_ENOUGH;
                break;
            }
            $config = config('pay');
            $kk_desc = $config['wallet_change_desc']['kk_exchange_jd'];
            $jd_desc = $config['wallet_change_desc']['jd_kk_into'];

            //数据处理
            DB::beginTransaction();
            try {
                //金币
                $this->kk->inc($userId, 0, 0, 40, 0-$kkNum, $kk_desc);

                //金豆
                $this->jd_model->inc($userId, 0, 9, $num, $jd_desc);

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();

                write_log('error_finance', 'kkBuyJd', ['msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //用户金豆流水列表
    public function jdDetailList($userId, $page, $page_size)
    {
        $list = $this->jd_model->getStreamList($userId, $page, $page_size);

        return [
            'list' => $list,
        ];
    }

    /**
     * 充值黑名单新增
     */
    public function rechargeBlackAdd($userId, $content, $payType){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            if(empty($userId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $info = $this->rechargeBlackModel->getRechargeBlack($userId, $payType);
            if(!empty($info)) {
                break;
            }
            $id = $this->rechargeBlackModel->addRechargeBlack($userId, $content, $payType);
            if(empty($id)) {
                $code = Hint::ERR_SYS_FAIL;
                break;
            }

        } while (false);
        return compact('code', 'msg', 'data');
    }

    /**
     * 临时充值黑名单新增
     */
    public function shortRechargeBlackAdd($userId, $content, $payType){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            if(empty($userId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            try{
                DB::beginTransaction();
                $id = $this->rechargeBlackModel->addRechargeFiveMinutesBlack($userId, $payType,  $content);
                if(empty($id)) {
                    $code = Hint::ERR_SYS_FAIL;
                    DB::rollBack();
                    break;
                }
            }catch(\Exception $e){
                DB::rollBack();
                $code = Hint::ERR_SYS_FAIL;
                write_log($this->errorRechargeLog,'ERROR 新增临时充值黑名单错误',['msg'=>$e->getMessage(),'data'=>['user'=>$userId,'content'=>$content,'paytype'=>$payType]]);
                break;
            }
            DB::commit();
            Redis::SET($this->payOrderFiveMinutes.$userId.':PAYTYPE:'.$payType,1);
            Redis::EXPIRE($this->payOrderFiveMinutes.$userId.':PAYTYPE:'.$payType, 300);
            Redis::INCRBY($this->payOrderFiveMinutesCount.$userId.':PAYTYPE:'.$payType,1);
            $endDay = Carbon::now()->endOfDay();
            $endTime = Carbon::now()->diffInSeconds($endDay);
            Redis::EXPIRE($this->payOrderFiveMinutesCount.$userId.':PAYTYPE:'.$payType,$endTime);
        } while (false);
        return compact('code', 'msg', 'data');
    }
    
    /**
     * 临时充值黑名单删除
     */
    public function shortRechargeBlackDel($id){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            if(empty($id)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            
            $this->rechargeBlackModel->shortRechargeBlackDel($id);

        } while (false);
        return compact('code', 'msg', 'data');
    }

    /**
     * 充值黑名单删除
     */
    public function rechargeBlackDel($id){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            if(empty($id)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            
            $this->rechargeBlackModel->delRechargeBlack($id);

        } while (false);
        return compact('code', 'msg', 'data');
    }

    /**
     * 留言板消耗钻石发留言
     */
    public function lybDiamandDecr($userId, $toUserId, $diamandNum, $content, $dataType, $dataId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            //用户钱包
            $wallet = $this->model_finance_user_wallet->get_wallet($userId);
            if(empty($wallet)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $diamandNum = abs($diamandNum);
            if($wallet['diamond_balance'] < $diamandNum ){
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }

            //记录
            $log = [
                'user_id' => $userId,
                'to_user_id' => $toUserId,
                'base_content' => $content,
                'diamand_num' => $diamandNum,
                'data_type' => $dataType,
                'data_id' => $dataId,
                'a_status' => 0,
                'b_status' => 0,
            ];

            $config = config('pay');
            $diamond_desc = $config['wallet_change_desc']['diamond_lyb_decr'];

            //数据处理
            DB::beginTransaction();
            try {
                //扣钻石
                $this->diamond->inc($userId, 0, 0, 81, 0-$diamandNum, $diamond_desc);

                //新增新增留言板
                $logId = $this->lybModel->addLybEvent($log);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_finance', 'lybDiamandDecr', ['userId'=>$userId, 'data_id'=>0, 'diamandNum'=>$diamandNum, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }

            //机审
            $res = $this->contentCheckService->auditContent($userId, $content);
            $this->lybModel->updateLybEventAStatus($logId, $res['content'], $res['third_result']);

            $data['log_id'] = $logId;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 新年活动2024奖励金豆
     */
    public function newYear2024JdIncr($user_id, $change_value, $data_id){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            //用户钱包
            $wallet = $this->model_finance_user_wallet->get_wallet($user_id);
            if(empty($wallet)){
                $code = Hint::PARAM_ERROR;
                break;
            }

            $config = config('pay');
            $jd_desc = $config['wallet_change_desc']['jd_newyear2024_incr'];
            //数据处理
            try {
                $this->jd_model->inc($user_id, $data_id, 13, $change_value, $jd_desc);
            } catch (\Exception $e) {
                write_log('error_finance', 'newYearJdIncr', ['user_id'=>$user_id, 'data_id'=>$data_id, 'change_value'=>$change_value, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //扣减/新增人气票
    public function newYearGiftNumChange($userId, $giftId, $changeValue, $type){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            //为负数时候增加人气票
            if($changeValue < 0) {
                $changeValue = abs($changeValue);
            }else{
                $changeValue = 0-$changeValue;
            }

            //数据处理
            DB::beginTransaction();
            try {
                //变更背包礼物
                $res = $this->giftBag_model->inc((int)$userId, 0, (int)$giftId, (int)$changeValue, 2012);
                if(!$res) {
                    DB::rollBack();
                    write_log('error_custom_send_ticket','sendInfo 变更背包礼物失败', [$userId, $giftId, $changeValue]);
                    $code = Hint::ERR_FAIL;
                    break;
                }
                //查询活动信息
                $customInfo = $this->customModel->getCumstomInfo($userId);
                
                //记录log
                $param = [
                    'user_id' => $userId,
                    'to_user_id' => 0,
                    'type' => $type,
                    'num' => $changeValue,
                    'created_at' => date('Y-m-d H:i:s',time()),
                    'custom_id' => isset($customInfo['id']) ? $customInfo['id'] : 0,
                ];
                $this->customModel->insertLog($param);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_custom_send_ticket', 'sendInfo', ['user_id'=>$userId, 'giftId'=>$giftId, 'changeValue'=>$changeValue, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 送彩蛋礼物奖励碎片
     */
    public function colorGiftDebrisIncr($userId, $giftId, $num, $giftNum){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            //数据处理
            try {
                $config = config('pay');
                $changeDesc = $config['wallet_change_desc']['debris_color_gift_incr'];

                $this->debris_model->inc($userId, $giftId, 1, $num, $changeDesc, $giftNum);
            } catch (\Exception $e) {
                write_log('error_finance', '送彩蛋礼物奖励碎片 colorGiftDebrisIncr', ['user_id'=>$userId, 'data_id'=>$giftId, 'change_value'=>$num, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 购买商品扣除碎片
     */
    public function buyGoodDebrisDecr($userId, $goodId, $changeValue, $dayNum){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            //用户钱包
            $wallet = $this->model_finance_user_wallet->get_wallet($userId);
            if(empty($wallet)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $changeValue = abs($changeValue);
            if($wallet['debris_balance'] < $changeValue ){
                $code = Hint::JD_NOT_ENOUGH;
                break;
            }

            //商品信息
            $skuId = 0;
            $goodInfo = $this->mall_model->getMallGoodByGoodsId($goodId);
            if(empty($goodInfo)) {
                $code = Hint::MALL_GOODS_LOWER;
                break;
            }
            $skuList = $this->mall_model->getSkuDataByGoods($goodId);
            if(empty($skuList[0])) {
                $code = Hint::MALL_GOODS_LOWER;
                break;
            }
            $skuId = $skuList[0]['sku_id'];
            //有效期
            $timeLimit = 86400 * $dayNum;

            $config = config('pay');
            $changeDesc = $config['wallet_change_desc']['debris_buy_good_decr'];

            //数据处理
            DB::beginTransaction();
            try {
                //扣碎片
                $this->debris_model->inc($userId, $goodId, 51, $changeValue, $changeDesc, $dayNum);

                //加商品
                $ret_data = $this->mall_model->shoppingAct(
                    $userId,
                    $userId,
                    $goodId,
                    $goodInfo['goods_name'],
                    $goodInfo['goods_type'],
                    $skuId,
                    $timeLimit,
                    0,
                    $timeLimit,
                    time(),
                    1
                );

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_finance', '购买商品扣除碎片 buyGoodDebrisDecr', ['user_id'=>$userId, 'data_id'=>$goodId, 'change_value'=>$changeValue, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 三国群英扣除钻石
     */
    public function lcDiamondDecr($user_id, $change_value){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            //用户钱包
            $wallet = $this->model_finance_user_wallet->get_wallet($user_id);
            if(empty($wallet)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $change_value = abs($change_value);
            if($wallet['diamond_balance'] < $change_value ){
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }

            $config = config('pay');
            $diamond_desc = $config['wallet_change_desc']['diamond_lassoCattle_decr'];
            //数据处理
            try {
                $this->diamond->inc($user_id, 0, 0, 83, 0-$change_value, $diamond_desc);
            } catch (\Exception $e) {
                write_log('error_finance', 'lcDiamondDecr', ['user_id'=>$user_id, 'data_id'=>0, 'change_value'=>$change_value, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 三国群英撤回增加钻石
     */
    public function lcBackDiamondIncr($user_id, $change_value){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $change_value = abs($change_value);
            $config = config('pay');
            $diamond_desc = $config['wallet_change_desc']['diamond_lassoCattle_back_incr'];
            //数据处理
            try {
                $this->diamond->inc($user_id, 0, 0, 84, $change_value, $diamond_desc);
            } catch (\Exception $e) {
                write_log('error_finance', 'lcDiamondDecr', ['user_id'=>$user_id, 'data_id'=>0, 'change_value'=>$change_value, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }


    /**
     * 三国群英押注扣除礼物或钻石
     */
    public function lcDiamondGiftDecr($userId, $giftId, $giftNum, $giftPrice){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $giftNum = abs($giftNum);
//            $needDiamond = $giftNum * 100;

            //用户钱包
            $wallet = $this->model_finance_user_wallet->get_wallet($userId);
            if(empty($wallet)){
                $code = Hint::PARAM_ERROR;
                break;
            }

//            if($wallet['diamond_balance'] < $needDiamond) {
//                $code = Hint::DIAMOND_NOT_ENOUGH;
//                break;
//            }

            //现有数量
            $giftBagInfo = $this->giftBag_model->get(['user_id'=>$userId,'gift_id'=>$giftId], true);
            $bagNum = empty($giftBagInfo['avail']) ? 0 : $giftBagInfo['avail'];
            $needDiamond = 0;//扣除钻石数量
            $needGiftNum = $giftNum;//扣除礼物数量
            if($bagNum < $giftNum){
                //判断钻石数量
                $needDiamond = ($giftNum - $bagNum)*$giftPrice;
                if($wallet['diamond_balance'] < $needDiamond) {
                    $code = Hint::DIAMOND_NOT_ENOUGH;
                    break;
                }
                $needGiftNum = $bagNum;
            }

            $config = config('pay');
            $diamond_desc = $config['wallet_change_desc']['diamond_lassoCattle_decr'];

            //数据处理
            DB::beginTransaction();
            try {
                //变更背包礼物
                if($needGiftNum > 0) {
                    $res = $this->giftBag_model->inc((int)$userId, 0, (int)$giftId, 0-$needGiftNum, 2007);
                    if(!$res) {
                        DB::rollBack();
                        write_log('error_lassoCattle','lcDiamondGiftDecr 变更背包礼物失败', [$userId, $giftId, $needGiftNum]);
                        $code = Hint::ERR_FAIL;
                        continue;
                    }
                }

                //扣钻石
                if($needDiamond > 0) {
                    $this->diamond->inc($userId, 0, 0, 83, 0-$needDiamond, $diamond_desc);
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_lassoCattle', 'lcDiamondGiftDecr', ['user_id'=>$userId, 'giftId'=>$giftId, 'giftNum'=>$giftNum, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                echo $e->getMessage();
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 三国群英撤回增加礼物
     */
    public function lcBackGiftIncr($userId, $giftId, $giftNum){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $giftNum = abs($giftNum);

            //数据处理
            DB::beginTransaction();
            try {
                //变更背包礼物
                $res = $this->giftBag_model->inc((int)$userId, 0, (int)$giftId, $giftNum, 2009);
                if(!$res) {
                    DB::rollBack();
                    write_log('error_lassoCattle','lcBackGiftIncr 变更背包礼物失败', [$userId, $giftId, $giftNum]);
                    $code = Hint::ERR_FAIL;
                    continue;
                }

//                $config = config('pay');
//                $diamond_desc = $config['wallet_change_desc']['diamond_lassoCattle_back_incr'];
//
//                //撤回钻石
//                if($giftNum > 0) {
//                    $this->diamond->inc($userId, 0, 0, 83, $giftNum * 100, $diamond_desc);
//                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_lassoCattle', 'lcBackGiftIncr', ['user_id'=>$userId, 'giftId'=>$giftId, 'giftNum'=>$giftNum, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                echo $e->getMessage();
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 三国群英批量奖励用户指定礼物
     */
    public function lcGiftNumChangeBatch($info, $gameNum){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($info['list'])) {
                break;
            }
            if(empty($info['gameNum']) || empty($info['winner']) || empty($info['giftId'])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //锁
            if (!redis_lock("lcGiftNumChangeBatch". $info['gameNum'], 86400)){
                $code = Hint::NOT_ALLOWED;
                break;
            }

            //数据处理
            foreach($info['list'] as $val) {
                try {
                    //变更背包礼物
                    $res = $this->giftBag_model->inc((int)$val['user_id'], 0, (int)$info['giftId'], (int)$val['num'], 2010, $gameNum);
                } catch (\Exception $e) {
                    write_log('error_grasslandSheep', 'lcGiftNumChangeBatch 三国群英批量奖励用户指定礼物 失败', ['gameNum'=>$info['gameNum'], 'giftId'=>$info['giftId'], 'val'=>$val, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                    $code = Hint::ERR_FAIL;
                }
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 三国群英批量发飘萍
     */
    public function lcFullScreenBatchV2($info){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($info['list'])) {
                break;
            }
            if(empty($info['gameNum']) || empty($info['winner'])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //锁
            if (!redis_lock("lcFullScreenBatchV2". $info['gameNum'])){
                $code = Hint::NOT_ALLOWED;
                break;
            }

            //飘萍
            $userIds = array_column($info['list'], 'user_id');
            $users = $this->user->get_users_by_ids($userIds);
            $users = array_column($users, 'nickname', 'user_id');
            foreach($info['list'] as $val) {
                try {
                    if($val['num'] >= $info['screenMin']) {
                        if(!empty($users[$val['user_id']])) {
                            $this->msgServices->sendFullScreen(64 ,null,['userName'=>$users[$val['user_id']], 'itemNum'=>$val['num'], 'giftPrice'=>$val['num']],[]);
                        }
                    }
                } catch (\Exception $e) {
                    write_log('error_grasslandSheep', 'lcFullScreenBatchV2 飘萍 失败', ['gameNum'=>$info['gameNum'], 'val'=>$val, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                    $code = Hint::ERR_FAIL;
                }
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 自定义活动累充奖励金豆
     */
    public function customRechargeJdIncr($user_id, $change_value, $data_id){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $config = config('pay');
            $jd_desc = $config['wallet_change_desc']['jd_custom_recharge_incr'];
            //数据处理
            try {
                $this->jd_model->inc($user_id, $data_id, 16, $change_value, $jd_desc);
            } catch (\Exception $e) {
                write_log('error_finance', 'customRankJdIncr', ['user_id'=>$user_id, 'data_id'=>$data_id, 'change_value'=>$change_value, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 自定义活动累充奖励钻石
     */
    public function rechargeDiamondIncr($user_id, $change_value, $data_id){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $config = config('pay');
            $diamond_desc = $config['wallet_change_desc']['diamond_custom_recharge_incr'];
            //数据处理
            try {
                $this->diamond->inc($user_id, 0, 0, 89, $change_value, $diamond_desc);
            } catch (\Exception $e) {
                write_log('error_finance', 'customRankJdIncr', ['user_id'=>$user_id, 'data_id'=>$data_id, 'change_value'=>$change_value, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 自定义活动榜单奖励金豆
     */
    public function customRankJdIncr($user_id, $change_value, $data_id){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $config = config('pay');
            $jd_desc = $config['wallet_change_desc']['jd_custom_rank_incr'];
            //数据处理
            try {
                $this->jd_model->inc($user_id, $data_id, 14, $change_value, $jd_desc);
            } catch (\Exception $e) {
                write_log('error_finance', 'customRankJdIncr', ['user_id'=>$user_id, 'data_id'=>$data_id, 'change_value'=>$change_value, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                $code = Hint::ERR_FAIL;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function setpayTypeList($userId){
        $config = $this->model_system->get_config();
        $pay_level_v1 = $this->model_system->getPaylevelConfig('pay_level_v1');
        $pay_level_v2 = $this->model_system->getPaylevelConfig('pay_level_v2');
        $pay_level_v3 = $this->model_system->getPaylevelConfig('pay_level_v3');
        $pay_level_v4 = $this->model_system->getPaylevelConfig('pay_level_v4');
        $pay_level_v5 = $this->model_system->getPaylevelConfig('pay_level_v5');
        //获取用户时间
        $userCreate=$this->services_user->user_regInfo($userId);
        //获取用户充值金额
        $userTotal=$this->service_pay->getRechargeTotal($userId);
        $userTotal=$userTotal/100;
        $list='';
        //获取用户礼物流水
        $giftTotal=$this->services_user->getGiftData($userId);
            if($userTotal>=$pay_level_v1[0] && $giftTotal>=$pay_level_v1[1] &&$userCreate>=$pay_level_v1[2]){
                $list .=$pay_level_v1[3]."|";
            }
           if($pay_level_v2[0]<=$userTotal && $pay_level_v2[1]<=$giftTotal && $pay_level_v2[2]<=$userCreate){
                $list .=$pay_level_v2[3]."|";
           }
            if($pay_level_v3[0]<=$userTotal && $pay_level_v3[1]<=$giftTotal && $pay_level_v3[2]<=$userCreate){
                $list .=$pay_level_v3[3]."|";
            }
            if($pay_level_v4[0]<=$userTotal && $pay_level_v4[1]<=$giftTotal  && $pay_level_v4[2]<=$userCreate){
                $list .=$pay_level_v4[3]."|";
            }
           if($userTotal>=$pay_level_v5[0] && $giftTotal>=$pay_level_v5[1] && $userCreate>=$pay_level_v5[2]) {
               $list .= $pay_level_v5[3];
           }
           // if(empty($list)){
           //     $list=empty($pay_level_v1[3])?$pay_level_v5[3]:$pay_level_v1[3];
           // }
        $list = array_unique(explode("|", $list));
        return empty($list)?[]:$list;

    }

    //代理转金币到指定用户  , $sms_code, $password
    public function agentGolodToUser($userId, $toUuid, $needNum)
    {

        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $needNum = abs($needNum);
            $info = $this->userAgentGolodModel->getUserAgent($userId);
            if(empty($info)) {
                $code = Hint::PARAM_ERROR;
                $msg = '非代理身份不可发送红包';
                break;
            }
            //用户信息
            $userInfo = $this->user->get_user($userId, true);
            if(empty($userInfo)) {
                $code = Hint::LOGIN_OUT;
                $msg = '用户信息获取失败';
                break;
            }
            //收用户信息
            $toUserInfo = $this->user->getUserByUuid($toUuid, true);
            if(empty($toUserInfo)) {
                $code = Hint::PARAM_ERROR;
                $msg = '该用户信息获取失败';
                break;
            }
            $toUserId = $toUserInfo['user_id'];
            //收用户 已注销 已封号
            $isForbid = $this->user->getBlockInfo($toUserId);
            if ($isForbid) {
                $code = Hint::USER_FORBID;
                $msg = '该用户已封禁，不可发送红包';
                break;
            }
            $isCancel = $this->user->getAccountCancel($toUserId);
            if ($isCancel || $toUserInfo['mobile_phone']==$toUserInfo['uuid']) {
                $code = Hint::USER_FORBID;
                $msg = '该用户已封禁，不可发送红包';
                break;
            }

            //判断是验证码还是密码
            $vType = 0;
//            if(!empty($sms_code)) {
//                $vType = 1;
//                //验证码
//                $smsKey = $this->agentSmsKey.$userInfo['phone'];
//                $sms_cache_code = Redis::get($smsKey);
//                if ($sms_cache_code != $sms_code) {
//                    $code = Hint::SMS_CODE_ERROR;
//                    break;
//                }
//            }elseif(!empty($password)) {
//                $vType = 2;
//                //密码
//                if(empty($info['password']) || $info['password']!==md5($password)) {
//                    $code = Hint::PASSWORD_ERROR;
//                    $msg = '代理密码错误';
//                    break;
//                }
//            }else{
//                $code = Hint::PARAM_ERROR;
//                $msg = '必要参数未传递';
//                break;
//            }

            //余额
            $userWallet = $this->model_finance_user_wallet->get_wallet($userId);
            if(empty($needNum) || $userWallet['kk_balance']<$needNum) {
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }

            //暂停代理操作
            $cacheKey = 'USER:AGENT:'.$userId;
            if (!redis_lock($cacheKey, 10)) {
                $code = Hint::SAME_TIME_NOT_REPEAT;
                break;
            }
            $config = config('pay');
            $diamond_desc = '代理转入-扣除金币';

            $log = [
                'user_id' => $toUserId,
                'from_user_id' => $userId,
                'diamond_num' => $needNum
            ];

            $logId = 0;

            DB::beginTransaction();
            try {
                //扣除
                $this->kk->inc($userId, $toUserId, 0, 89, 0-$needNum, $diamond_desc);

                //添加记录
                $logId = $this->agentG_model->createAgentDLog($log);

                DB::commit();
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                DB::rollBack();
            }
            redis_unlock($cacheKey);

//            if($vType == 1) {
//                Redis::DEL($smsKey);
//            }

            //成功发信息
            if($code == Hint::SUCCESS) {
                $msg = $userInfo['nickname'].'给你发送了一个金币红包，点击查收';
                $this->msgServices->agentKKSendMsg($userId, $toUserId, $msg, $logId, $needNum);
                // $this->msgServices->send_text_msg($userId, $toUserId, $msg);
                $msg = '您已经成功转账给'.$toUserInfo['nickname'].' , '.$needNum.'金币';
                $this->msgServices->send_sys_text_msg_kk($userId, $msg);

            }

            $this->userReceiveAgentgolod($toUserId, $logId);

        } while (false);
        return compact('code', 'msg', 'data');
    }

    //用户金币领取转入的钻石
    public function userReceiveAgentGolod($userId, $logId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $logInfo = $this->agentG_model->getAgentDLog($logId);
            if(empty($logInfo)) {
                $code = Hint::PARAM_ERROR;
                $msg = '红包信息获取失败';
                break;
            }
            if($logInfo['agentd_type'] != 1) {
                $code = Hint::PARAM_ERROR;
                $msg = '红包已领取';
                break;
            }

            //暂停代理操作
            $cacheKey = 'USER:AGENTJDRECEIVE:'.$logId;
            if (!redis_lock($cacheKey, 10)) {
                $code = Hint::SAME_TIME_NOT_REPEAT;
                break;
            }
            $config = config('pay');
            $diamond_desc = '代理转入-获得金币';

            DB::beginTransaction();
            try {
                //更新记录
                $this->agentG_model->updateAgentDLog($logId, ['agentd_type'=>2]);

                //增加
                $this->kk->inc($logInfo['user_id'], $logInfo['from_user_id'], 0, 88, $logInfo['diamond_num'], $diamond_desc);

                DB::commit();
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                DB::rollBack();
                redis_unlock($cacheKey);
                break;
            }
            redis_unlock($cacheKey);

            $data['num'] = $logInfo['diamond_num'];

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //获取用户代理金币交易记录
    public function userAgentGLog($page, $page_size, $userId, $streamType, $timeSt, $timeEd)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $where['user_id'] = $userId;
            //转出
            if($streamType == 1) {
                $where['diamond_type'] = [89];
            }
            //兑换
            if($streamType == 2) {
                $where['diamond_type'] = [88];
            }
            $where['time_st'] = $timeSt;
            $where['time_ed'] = $timeEd;

            $list = $this->agentG_model->getAgentjStreamList($where, $page, $page_size);
            $listEx = [];
            if(!empty($list)) {
                $userIds = array_unique(array_column($list, 'from_user_id'));
                $users = $this->user->get_users_by_ids($userIds);
                $users = array_column($users, null, 'user_id');

                foreach($list as $key=>$val) {
                    $val['to_uuid'] = 0;
                    if($streamType == 1) {
                        $val['to_uuid'] = empty($users[$val['from_user_id']]['user_uid']) ? 0 : $users[$val['from_user_id']]['user_uid'];
                    }
                    $item = [];
                    $item['stream_id'] = $val['stream_id'];
                    $item['user_id'] = $val['user_id'];
                    $item['change_value'] = $val['kk_value'];
                    $item['diamond_type'] = $val['kk_type'];
                    $item['change_timestamp'] = $val['change_timestamp'];
                    if($streamType == 1) {
                        $item['to_uuid'] = $val['to_uuid'];
                    }
                    $listEx[] = $item;
                }
            }

            $data['list'] = $listEx;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //用户代理状态
    public function agentGolodStatus($userId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];

        do {
            $info = $this->userAgentGolodModel->getUserAgent($userId);
            $data['status'] = empty($info['status']) ? 0 : $info['status'];
            $data['rate'] = empty($info['rate']) ? 0 : $info['rate'];
            $data['hasPass'] = empty($info['password']) ? 0 : 1;

        } while (false);

        return compact('code', 'msg', 'data');
    }
    //获取kk币流水列表
    public function getExchangeKkStreamList($page, $page_size)
    {

        $userInfo = $this->user->get_current_user();
        if (!empty($userInfo)) {
            $userId = $userInfo['user_id'];
            $diamondData = $this->kk->exchangestreams($userId, $page, $page_size);
            return [
                'list'=>$diamondData,
                'page_index'=>$page,
                'page_count'=>count($diamondData),
                'page_size'=>$page_size
            ];
        }
        return ['list'=>[],'page_index'=>$page,'page_count'=>0,'page_size'=>$page_size];
    }
}
